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文件包路径。
八.启动项目进行测试
项目结构: