项目搭建[3]springBoot引入Mybatis

Mybatis引入

pom文件配置

在dependencies节点下引入Mybatis的引用

1
2
3
4
5
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>

application.yaml配置

application.yaml下增加如下配置,classpath是resources目录下的相对路径。type-aliases-package

1
2
mybatis:
mapper-locations: classpath:mapping/*Mapper.xml

Application增加扫描

在Application入口类中增加注解@MapperScan,指向mapper文件的路径

1
2
3
4
5
6
7
8
@MapperScan("com.example.mapper")
@SpringBootApplication
public class DemoApplication {

public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

新增PO类

1
2
3
4
5
6
@Data
public class UserPO {
private Integer id;
private String username;
private String password;
}

新增Mapper类

1
2
3
4
@Mapper
public interface UserMapper {
UserPO findById(int id);
}

新增Mapper.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?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.mapper.UserMapper">

<resultMap id="BaseResultMap" type="com.example.po.UserPO">
<result column="id" jdbcType="INTEGER" property="id" />
<result column="username" jdbcType="VARCHAR" property="username" />
<result column="password" jdbcType="VARCHAR" property="password" />
</resultMap>

<select id="findById" resultType="com.example.po.UserPO">
select * from user where id = #{id}
</select>

</mapper>