前段时间项目比较紧张,今天终于有空继续更新这个专题了。在这里记录下Spring Boot中整合MyBatis的步骤,搜了一下Spring Boot整合MyBatis的文章,不少都有些过时了。目前spring boot已经有mybatis starter支持,大大降低了接入成本。下面就来详细介绍如何在Spring Boot中整合MyBatis,并通过druid管理数据库连接池。
整合MyBatis和Druid
新建Spring Boot项目
-
pom.xml
中引入依赖- 这里用到spring-boot-starter基础和spring-boot-starter-test用来做单元测试验证数据访问
- 引入连接mysql的必要依赖mysql-connector-java
- 引入整合MyBatis的核心依赖mybatis-spring-boot-starter
- 这里不引入spring-boot-starter-jdbc依赖,是由于mybatis-spring-boot-starter中已经包含了此依赖
- 引入alibaba的druid依赖
<!--MyBatis 及 插件依赖 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.21</version> </dependency> <!-- druid依赖--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.11</version> </dependency>
在application.properties中配置mysql的连接配置,如下:
druid.url=jdbc\:mysql://localhost:3306/job?useUnicode=true&characterEncoding=UTF-8
druid.driver-class=com.mysql.jdbc.Driver
druid.username=root
druid.password=123456
druid.initial-size=1
druid.min-idle=1
druid.max-active=20
druid.test-on-borrow=true
- 引入DruidAutoConfiguration
@Configuration
@EnableConfigurationProperties(DruidProperties.class)
@ConditionalOnClass(DruidDataSource.class)
@ConditionalOnProperty(prefix = "druid", name = "url")
@AutoConfigureBefore(DataSourceAutoConfiguration.class)
public class DruidAutoConfiguration {
@Autowired
private DruidProperties properties;
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(properties.getUrl());
dataSource.setUsername(properties.getUsername());
dataSource.setPassword(properties.getPassword());
if (properties.getInitialSize() > 0) {
dataSource.setInitialSize(properties.getInitialSize());
}
if (properties.getMinIdle() > 0) {
dataSource.setMinIdle(properties.getMinIdle());
}
if (properties.getMaxActive() > 0) {
dataSource.setMaxActive(properties.getMaxActive());
}
dataSource.setTestOnBorrow(properties.isTestOnBorrow());
try {
dataSource.init();
} catch (SQLException e) {
throw new RuntimeException(e);
}
return dataSource;
}
}
- 引入DruidProperties
@ConfigurationProperties(prefix = "druid")
public class DruidProperties {
private String url;
private String username;
private String password;
private String driverClass;
private int maxActive;
private int minIdle;
private int initialSize;
private boolean testOnBorrow;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDriverClass() {
return driverClass;
}
public void setDriverClass(String driverClass) {
this.driverClass = driverClass;
}
public int getMaxActive() {
return maxActive;
}
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
public int getMinIdle() {
return minIdle;
}
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
public int getInitialSize() {
return initialSize;
}
public void setInitialSize(int initialSize) {
this.initialSize = initialSize;
}
public boolean isTestOnBorrow() {
return testOnBorrow;
}
public void setTestOnBorrow(boolean testOnBorrow) {
this.testOnBorrow = testOnBorrow;
}
}
使用MyBatis
在Mysql中创建User表,包含id(BIGINT)、name(VARCHAR)、age(INT)字段。同时,创建映射对象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)
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());
}
}
后记
上面主要介绍了利用注解来实现mapper的情况,下一篇文章将会介绍在spring boot集成mybatis的xml形式,以及方便的分页插件,敬请期待。
【参考链接】
http://blog.didispace.com/springbootmybatis/
http://blog.csdn.net/CSDN3436/article/details/68491069