目录
本篇所有代码均来翟永超的博客:
- 本文仅供自己学习之用
spring boot 整合mybatis
- 工作中所使用的框架spring boot + mybatis
- 工作之余看到了搭建方法,顺便把它放到这里,以供以后参考
pom.xml依赖
- 在pom.xml引入所需要的依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.6.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.21</version>
</dependency>
</dependencies>
application.properties配置
- 在application.properties中配置mysql的连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
使用MyBatis
- 在Mysql中创建User表,包含id(BIGINT)、name(INT)、age(VARCHAR)字段。同时,创建映射对象User
public class User {
private Long id;
private String name;
private Integer age;
// 省略getter和setter
}
- 创建User映射的操作UserMapper,为了后续单元测试验证,实现插入和查询操作
@Mapper
public interface UserMapper {
@Select("SELECT * FROM USER WHERE NAME = #{name}")
User findByName(@Param("name") String name);
@Insert("INSERT INTO USER(NAME, AGE) VALUES(#{name}, #{age})")
int insert(@Param("name") String name, @Param("age") Integer age);
}
- 创建Spring Boot主类
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
- 创建单元测试
- 测试逻辑:插入一条name=AAA,age=20的记录,然后根据name=AAA查询,并判断age是否为20
- 测试结束回滚数据,保证测试单元每次运行的数据环境独立
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@Transactional
public class ApplicationTests {
@Autowired
private UserMapper userMapper;
@Test
@Rollback
public void findByName() throws Exception {
userMapper.insert("AAA", 20);
User u = userMapper.findByName("AAA");
Assert.assertEquals(20, u.getAge().intValue());
}
}