Mybatis是常用的持久层框架,体验Spring Boot的同时不免需要将Mybatis整合进去
引入maven依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>2.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
</dependencies>
本文用的是HikariCP连接池,也可以使用其他连接池
数据源属性
在application.properties中添加
datasource.pool.jdbcUrl=jdbc:mysql://
datasource.pool.username=root
datasource.pool.password=
datasource.pool.maximumPoolSize=100
配置一个Mybatis配置
@Configuration
@EnableTransactionManagement
public class MybatisConfig {
@Bean
@ConfigurationProperties(prefix = "datasource.pool")
public DataSource dataSource(){
return new HikariDataSource();
}
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
return sqlSessionFactoryBean.getObject();
}
}
@EnableTransactionManagement开启事务管理
配置mapper
@Mapper
public interface StudentMapper {
@Select("select * from student")
@ResultType(value = Student.class)
List<Student> getAll();
}
@ComponentScan会自动扫描@Mapper注解的类
也可以用@MapperScan来指定
@MapperScan(basePackages = "com.drafthj.test")
public class MybatisConfig {
...
}
接下来就可以直接使用Mapper类来操作了
@Autowired
private StudentMapper studentMapper;
使用xml文件配置
1、可以在application.properties中mybatis.config-location=来指定文件位置
2、sqlSessionFactoryBean.setConfigLocation()