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連接池若未,也可以使用其他連接池
數(shù)據(jù)源屬性
在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()