Spring Boot 整合Mybatis
Mybatis是用的比較多的ORM開源框架,傳統的Spring中整合Mybatis要引入各種jar包,還要注意jar包的版本,工程中還需要一對的配置文件。下面來看看在Spring Boot中使用Mybatis有多麼的簡單。
一.創建工程
具體創建過程可以參考第一篇文章,注意在選擇組件的時候獎mybatis加上。
二.配置工程文件
##mapper文件位置
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
mybatis.type-aliases-package=com.example.demo.entity
##配置數據源
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = root
spring.datasource.password = 000000
三.創建表對應的實體類
package com.example.demo.entity;
public class User {
private int id;
private String name;
private int age;
private String password;
。。。
。。。
}
四.創建mapper類(相當於dao)
package com.example.demo.mapper;
import com.example.demo.entity.User;
public interface UserMapper {
// 方法的名稱要和mapper.xml中的id相對應
public User getUserById(int id);
}
五.創建mapper.xml映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.demo.mapper.UserMapper">
<resultMap type="com.example.demo.entity.User" id="UserResultMap">
<id column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="password" property="password" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
</resultMap>
<select id="getUserById" parameterType="java.lang.Integer" resultMap="UserResultMap">
select * from t_user where id = #{id}
</select>
</mapper>
注意,這邊的namespace是mapper文件的路徑,select中的id對應mapper文件中的方法名。
六.創建控制器
package com.example.demo.controller;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
@RestController
@RequestMapping("/user")
public class UserController {
@Resource
private UserMapper userMapper;
@RequestMapping("/getUserById")
public User getUserById(@RequestParam("id") int id){
return userMapper.getUserById(id);
}
}
七.修改項目的啓動類
package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@MapperScan指明mapper文件包路徑。
八.啓動項目進行測試
項目結構: