官方文档https://mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/#
步骤如下:
1、创建项目,导入依赖
使用IDEA创建一个springboot项目,选择web、jdbc、mysqldriver模块,再导入mybatis依赖:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
2、在application.yaml配置文件中配置连接数据库需要的信息并配置mybatis,(有时需要在主启动类或者配置类上加@MapperScan注解,即使加了@Mapper注解也没用,必须要@MapperScan,原因不明,可能是版本的问题)
spring:
#配置数据库连接信息
datasource:
username: root
password: root
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
#给包中的实体类起别名
type-aliases-package: com.wt.pojo
#告诉mybatis mapper配置文件在哪
mapper-locations: classpath:mybatis/mapper/*.xml
3、写实体类(pojo)
这里以User为例
package com.wt.pojo;
public class User {
private int id;
private String name;
private String pwd;
//有参无参构造函数,getter与setter
}
4、写实体类对应的mapper接口(mapper)
注意@Mapper注解,这个注解相当于在mybatis核心配置文件中“注册“这个mapper
package com.wt.mapper;
import com.wt.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper//这个注解相当于在mybatis核心配置文件中“注册这个mapper”
@Repository//dao层的Component,托管给springboot
public interface UserMapper {
//查询所有用户
List<User> getAllUsers();
//根据id查询用户
User getUserById(int id);
}
5、写mapper接口的实现(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.wt.mapper.UserMapper">
<select id="getAllUsers" resultType="User">
select * from mybatis.user;
</select>
<select id="getUserById" parameterType="int" resultType="User">
select from mybatis.user where id = #{id};
</select>
</mapper>
6、测试
这里为了偷懒没写service层直接在controller层调dao层了
package com.wt.controller;
import com.wt.mapper.UserMapper;
import com.wt.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class TestMybatis {
@Autowired
private UserMapper userMapper;
@GetMapping("/userlist")
public List<User> getAllUsers(){
return userMapper.getAllUsers();
}
}
结果:浏览器访问http://localhost:8080/userlist能拿到数据