文章使用版本為 Spring Boot 2.1.x
前言
在 Spring Boot 入門系列(四) 使用JdbcTemplate訪問數(shù)據(jù)庫 中我們介紹了 JdbcTemplate 的簡單用法匈挖,當(dāng)項目比較小或者不怎么需要使用數(shù)據(jù)庫時整以,JdbcTemplate 是個不錯的選擇炼吴,但是如果項目比較大時粱锐,我們希望使用一些更加強大的框架,比如今天我們介紹的 MyBatis钮呀。
Mybatis通常有兩種使用方式
- 在接口文件上寫注解來映射SQL語句
- 通過XML文件來映射SQL語句
今天我們先來學(xué)習(xí)第一種方式剑鞍,使用注解
添加依賴
在spring boot下使用 mybatis,首先我們要添加 mybatis 的依賴爽醋,其中 pagehelper 是第三方的一個分頁插件蚁署。
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<!--mybatis分頁插件-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
配置application.yml
application.yml的配置包括兩部分,一部分是數(shù)據(jù)源的配置蚂四,另一部分就是Mybatis的各種配置光戈。
spring:
datasource:
url: jdbc:mysql://127.0.0.1:3306/spring_boot_learn?useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&autoReconnect=true&useSSL=true
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
hikari:
minimum-idle: 2
maximum-pool-size: 5
mybatis:
configuration:
default-executor-type: reuse
default-statement-timeout: 2
新建接口類
package org.schhx.springbootlearn.dao;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.schhx.springbootlearn.module.User;
public interface UserMapper {
@Insert("insert into user (id, username, age) values(#{id}, #{username}, #{age})")
int insert(User record);
@Delete("delete from user where id = #{id}")
int deleteByPrimaryKey(String id);
@Update("update user set username = #{username}, age = #{age} where id = #{id}")
int updateByPrimaryKey(User record);
@Select("select * from user where id = #{id}")
User selectByPrimaryKey(String id);
}
掃描接口類
現(xiàn)在我們還需要把接口類交給Spring來管理哪痰,掃描接口類的方式有兩種
- 在接口類上加上注解 @Mapper。
- 在項目啟動類上加注解 @MapperScan(basePackages = {"org.schhx.springbootlearn.dao"})久妆,它會掃描指定包下的所有接口類妒御。
建議使用第二種方式。
測試
到此為止镇饺,我們已經(jīng)把所有的配置都配置完畢,可以通過一個測試文件來測試是否能夠正常訪問數(shù)據(jù)庫送讲。
package org.schhx.springbootlearn.dao;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.schhx.springbootlearn.module.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.UUID;
import static org.junit.Assert.*;
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
private UserMapper userMapper;
@Test
@Transactional
public void insert() throws Exception {
User user = new User()
.setId(UUID.randomUUID().toString())
.setUsername("張三")
.setAge(20);
int result = userMapper.insert(user);
Assert.assertEquals(1, result);
}
@Test
@Transactional
public void deleteByPrimaryKey() throws Exception {
User user = new User()
.setId(UUID.randomUUID().toString())
.setUsername("張三")
.setAge(20);
userMapper.insert(user);
int result = userMapper.deleteByPrimaryKey(user.getId());
Assert.assertEquals(1, result);
}
@Test
@Transactional
public void updateByPrimaryKey() throws Exception {
User user = new User()
.setId(UUID.randomUUID().toString())
.setUsername("張三")
.setAge(20);
userMapper.insert(user);
user.setUsername("李四")
.setAge(30);
userMapper.updateByPrimaryKey(user);
User result = userMapper.selectByPrimaryKey(user.getId());
Assert.assertEquals(user, result);
}
@Test
public void selectByPrimaryKey() throws Exception {
}
}