springboot整合mybatis

引入依赖

1
2
3
4
5
6
7
8
9
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.2</version>
</dependency>

配置

1
2
3
4
5
6
7
8
9
10
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: root

mybatis:
#加载mapper文件
mapper-locations: classpath:mapper/*.xml

实体类

1
2
3
4
5
6
7
public class User {

private Long id;
private String username;
private String password;
// getter setter ...
}

mapper接口

1
2
3
4
5
6
@Mapper
public interface UserMapper {
// 如果不写mapper文件的话可以使用注解方式
// @Select("select * from user where id = #{id}")
User selectById(Long id);
}

mapper文件

1
2
3
4
5
6
7
8
<?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="org.example.dao.UserMapper">

<select id="selectById" parameterType="long" resultType="org.example.domain.User">
select * from user where id = #{id}
</select>
</mapper>

扫描mapper接口

1
2
3
4
5
6
7
8
@MapperScan(value = {"org.example.dao"})
@SpringBootApplication
public class MyApplication {

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

测试

1
2
3
4
5
6
7
8
9
10
11
12
@SpringBootTest
public class MyTests {

@Autowired
UserMapper userMapper;

@Test
public void test() {
User user = userMapper.selectById(1L);
System.out.println(user);
}
}