1. 导入依赖
- 我使用MySQL,需要导入MySQL的驱动依赖
- 此外要在SpringBoot中使用Mybatis,则需要导入Mybatis启动器
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.2</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.33</version></dependency>
需要注意版本对应关系,我是用springboot2.7.14,则需要导入2.2或2.3的Mybatis启动器
2. 配置文件
在springboot的yaml配置文件中把连接数据库所需的spring.datasource和mybatis.mapper-locations配置好。
- mapper-locations我设置的是classpath:mapper/*.xml,一般都是在
resource目录下创建一个mapper文件夹,然后把所有的mapper.xml放进去。因此mapper-locations设置为classpath:mapper/*.xml的意思就是扫描mapper文件夹下的所有xml文件作为mybatis的mapper - spring.datasource则就是数据库连接所需的driver、url、username、password
mybatis:mapper-locations: classpath:mapper/*.xml
spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://localhost:3306/mytestusername: rootpassword: root
3. 业务场景
dao层创建一个Mapper接口,注意需要用@Mapper标记
@Mapper
public interface UserMapper {User getUserByID(int id);
}
对应的在resource/mapper下创建对应的Mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wonder.mapper.UserMapper"><select id="getUserByID" parameterType="int" resultType="com.wonder.entity.User">select * from users where id=#{id}</select>
</mapper>
其中用到的entity
package com.wonder.entity;
public class User {private long id;private String name;private String username;private String password;private java.sql.Timestamp createtime;private long roleid;public long getId() {return id;}public void setId(long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public java.sql.Timestamp getCreatetime() {return createtime;}public void setCreatetime(java.sql.Timestamp createtime) {this.createtime = createtime;}public long getRoleid() {return roleid;}public void setRoleid(long roleid) {this.roleid = roleid;}
}
用到的数据库表和其中的数据
4. Service层和Controller层
public interface UserService {User getUserByID(int id);
}
@Service
public class UserServiceImpl implements UserService {@AutowiredUserMapper userMapper;@Overridepublic User getUserByID(int id) {return userMapper.getUserByID(id);}
}
@Controller
public class UserController {@AutowiredUserService userService;@RequestMapping("/getUser")@ResponseBodypublic User getUserByID(@RequestParam("id") int id){return userService.getUserByID(id);}
}
5. 测试效果
启动程序,浏览器中输入http://localhost:8080/getUser?id=2
6. 额外记录
记录下在IDEA中最好安装MyBatisX插件,能够方便的在IDEA中进行mapper和xml之间的跳转。相当好用。