POM文件:
<properties>
<mybatis.starter.version>1.3.2</mybatis.starter.version>
</properties>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis.starter.version}</version>
</dependency>
YAML文件:
spring:
profiles:
active: dev
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
druid:
master:
url: jdbc:mysql://localhost:3306/study?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull
username: root
password: root
slave:
enable: true
url: jdbc:mysql://localhost:3306/study?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&zeroDateTimeBehavior=convertToNull
username: root
password: root
mybatis:
type-aliases-package: cn.xhh.dev.entity
mapperLocations: classpath:mappers/*.xml
在resources目录中新建mappers目录,在mappers目录中新建UserMapper.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="cn.xhh.dev.mapper.UserMapper">
<sql id="user_all">
ID, NAME, LEVEL
</sql>
<select id="getUser" resultType="cn.xhh.dev.entity.UserEntity">
SELECT
<include refid="user_all"></include>
FROM USER WHERE ID = #{id,jdbcType=INTEGER}
</select>
</mapper>
新建mapper包,与controller同级,并在mapper包下新建接口类:
package cn.xhh.dev.mapper;
import cn.xhh.dev.entity.UserEntity;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface UserMapper {
public UserEntity getUser(int id);
}
新建entity包,与mapper包同级,并在entity包下新建pojo类:
package cn.xhh.dev.entity;
import lombok.Data;
@Data
public class UserEntity {
private int id;
private String name;
private int level;
}
编写一个Controller类进行测试:
package cn.xhh.dev.controller;
import cn.xhh.dev.common.annotation.DataSource;
import cn.xhh.dev.common.enums.DataSourcesType;
import cn.xhh.dev.entity.UserEntity;
import cn.xhh.dev.mapper.UserMapper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("user")
public class MybatisController {
private UserMapper userMapper;
public MybatisController(UserMapper userMapper) {
this.userMapper = userMapper;
}
@RequestMapping("getUser")
public String getUser(@RequestParam("id") Integer id){
UserEntity user = userMapper.getUser(id);
return user.toString();
}
}
浏览器访问:
http://localhost:8081/user/getUser?id=1
|