Spring Boot集成mybatis
集成MyBatis
1. 引入依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
2. 配置application.properties
#数据源配置
spring.datasource.url=jdbc:mysql://localhost:3306/ncp?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#mybatis配置
mybatis.typeAliasesPackage=com.example.demo.entity
mybatis.mapperLocations=classpath:mapper/*.xml
#驼峰命名,将数据库字段与实体类字段使用驼峰命名对应(db: create_date ----> entity: createDate)
mybatis.configuration.map-underscore-to-camel-case=true
#打印sql语句
logging.level.com.example.demo.dao=debug
3. 配置mybatis相关注解
@MapperScan("com.example.demo.dao")
@SpringBootApplication
public class SpringBootDemoApplication
@MapperScan: 配置dao层的扫描接口,如果配置dao接口上,则只对配置的dao接口进行扫描.如果想要全局配置则可以在Application上进行配置,在Application上配置则扫描配置包下的全部接口
其他注解和spring中整合mybatis一样:
@Repository: 标记在dao接口上
@Service: 标记在service接口上
4. 配置XXXmapper.xml
在resources目录下创建mapper/xxxMapper.xml即可
MyBatis集成分页插件pagehelper
1. 引入依赖
<!-- MyBatis集成分页插件pagehelper -->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
2. 配置application.properties
#pagehelper分页插件配置
pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql
3. 在service中层使用分页
PageHelper.startPage(pageNo, pageSize);
pageNo: 表示当前页(1, 2, 3, 4, 5 …)
pageSize: 表示当前页显示多少条记录
MyBatis多数据源配置(主从数据库)
1.DataSourceConfig
主数据源 MasterDataSourceConfig
@Configuration
@MapperScan(basePackages = MasterDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "masterSqlSessionFactory")
public class MasterDataSourceConfig {
private Logger logger = LoggerFactory.getLogger(this.getClass());
public static final String PACKAGE = "com.example.demo.dao.master";
@Value("${master.datasource.url}")
private String url;
@Value("${master.datasource.username}")
private String username;
@Value("${master.datasource.password}")
private String password;
@Value("${master.datasource.driver-class-name}")
private String driverClass;
@Value("${master.mybatis.mapperLocations}")
private String mapperLocation;
@Value("${master.mybatis.typeAliasesPackage}")
private String aliasesPackage;
@Bean(name = "masterDataSource")
@Primary
public DataSource masterDataSource(){
logger.info("url: " + url);
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setDriverClassName(driverClass);
return dataSource;
}
@Bean(name = "masterDataSourceTransactionManager")
@Primary
public DataSourceTransactionManager masterDataSourceTransactionManager(){
return new DataSourceTransactionManager(masterDataSource());
}
@Bean(name = "masterSqlSessionFactory")
@Primary
public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(masterDataSource);
//设置mapper路径
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocation));
//设置别名实体类包
sqlSessionFactoryBean.setTypeAliasesPackage(aliasesPackage);
org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
//设置驼峰命名
configuration.setMapUnderscoreToCamelCase(true);
sqlSessionFactoryBean.setConfiguration(configuration);
return sqlSessionFactoryBean.getObject();
}
}
从数据源 ClusterDataSourceConfig
@Configuration
@MapperScan(basePackages = ClusterDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "clusterSqlSessionFactory")
public class ClusterDataSourceConfig {
public static final String PACKAGE = "com.example.demo.dao.cluster";
@Value("${cluster.datasource.url}")
private String url;
@Value("${cluster.datasource.username}")
private String username;
@Value("${cluster.datasource.password}")
private String password;
@Value("${cluster.datasource.driver-class-name}")
private String driverClass;
@Value("${cluster.mybatis.mapperLocations}")
private String mapperLocation;
@Value("${cluster.mybatis.typeAliasesPackage}")
private String aliasesPackage;
@Bean(name = "clusterDataSource")
public DataSource clusterDataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setDriverClassName(driverClass);
return dataSource;
}
@Bean(name = "clusterDataSourceTransactionManager")
public DataSourceTransactionManager clusterDataSourceTransactionManager(){
return new DataSourceTransactionManager(clusterDataSource());
}
@Bean(name = "clusterSqlSessionFactory")
public SqlSessionFactory clusterSqlSessionFactory(@Qualifier("clusterDataSource") DataSource clusterDataSource) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(clusterDataSource);
//设置mapper路径
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(mapperLocation));
//设置别名实体类包
sqlSessionFactoryBean.setTypeAliasesPackage(aliasesPackage);
org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
//设置驼峰命名
configuration.setMapUnderscoreToCamelCase(true);
sqlSessionFactoryBean.setConfiguration(configuration);
return sqlSessionFactoryBean.getObject();
}
}
多数据源配置的时候注意,必须要有一个主数据源。@Primary 标志这个 Bean 如果在多个同类 Bean 候选时,该 Bean 优先被考虑。
配置多数据源总结:
- 主要是配置不同数据源的sqlSessionFactory,配置不同的sqlSessionFactory,则需要配置DataSource以及DataSourceTransactionManager等.
- 配置不同的数据源sqlSessionFactory的mapper文件路径和对应实体包等信息
- 配置不同数据源的dao接口包路径
MyBatis多数据源连接池配置(Druid)
配置多数据连接池Druid,和多数据源配置一样.只需要对DataSource进行调整,对DataSource增加相关配置信息
@Value("${spring.datasource.initialSize}")
private int initialSize;
@Value("${spring.datasource.minIdle}")
private int minIdle;
@Value("${spring.datasource.maxActive}")
private int maxActive;
@Value("${spring.datasource.maxWait}")
private int maxWait;
@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
@Value("${spring.datasource.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
@Value("${spring.datasource.validationQuery}")
private String validationQuery;
@Value("${spring.datasource.testWhileIdle}")
private boolean testWhileIdle;
@Value("${spring.datasource.testOnBorrow}")
private boolean testOnBorrow;
@Value("${spring.datasource.testOnReturn}")
private boolean testOnReturn;
@Value("${spring.datasource.poolPreparedStatements}")
private boolean poolPreparedStatements;
@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
private int maxPoolPreparedStatementPerConnectionSize;
@Value("${spring.datasource.filters}")
private String filters;
@Value("${spring.datasource.connectionProperties}")
private String connectionProperties;
@Value("${spring.datasource.useGlobalDataSourceStat}")
private boolean useGlobalDataSourceStat;
@Bean(name = "masterDataSource")
@Primary
public DataSource masterDataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setDriverClassName(driverClass);
configuration(dataSource);
return dataSource;
}
private void configuration(DruidDataSource dataSource) {
dataSource.setInitialSize(initialSize);
dataSource.setMinIdle(minIdle);
dataSource.setMaxActive(maxActive);
dataSource.setMaxWait(maxWait);
dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
dataSource.setValidationQuery(validationQuery);
dataSource.setTestWhileIdle(testWhileIdle);
dataSource.setTestOnBorrow(testOnBorrow);
dataSource.setTestOnReturn(testOnReturn);
dataSource.setPoolPreparedStatements(poolPreparedStatements);
dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
dataSource.setUseGlobalDataSourceStat(useGlobalDataSourceStat);
try {
dataSource.setFilters(filters);
} catch (SQLException e) {
System.err.println("druid configuration initialization filter: "+ e);
}
dataSource.setConnectionProperties(connectionProperties);
}
相关配置属性和单数据源配置Druid一样,在application.properties中设置
Druid过滤器和servlet和单数据源Druid配置无差别