Maven依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
application.yaml
设置mybatis的*.xml文件位置
spring:
datasource:
name: renaissance
url: jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&useSSL=false&allowPublicKeyRetrieval=true
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapper/*.xml
编写mapper.xml文件
以user-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.test.renaissance.module.repository.UserMapper">
<resultMap id="BaseResultMap" type="com.zkpy.renaissance.module.bean.User">
<id column="id" property="id" jdbcType="INTEGER"/>
<result column="name" property="name" jdbcType="VARCHAR"/>
<result column="age" property="age" jdbcType="INTEGER"/>
</resultMap>
<sql id="user_information">
id, name, age
</sql>
<select id="getUser" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="user_information"/>
from user where id=#{id};
</select>
</mapper>
<mapper>标签的的namespace对应了Dao层中的Mapper接口
Dao层Mapper接口
@Mapper
public interface UserMapper {
public User getUser(@Param("id") int id);
}
接口实现
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User getUser(int id) {
return userMapper.getUser(id);
}
}
调用接口
@Controller
@RestController
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping(value = "/get")
public String getUser(@RequestParam("id") int id){
return new Gson().toJson(userService.getUser(id));
}
}