Mybatis是一个使用广泛的ORM框架,相信大家都使用的很熟练的。但绝大部分朋友应该都使用XML进行配置。在springboot中,为了方便或者减少xml文件的数量,也可以选择完全通过代码来配置mybatis。下面就来说说如果通过java代码配置mybatis。
配置起来也非常简单,只需一个类,而且不容易出错。
首先把原来配置mybatis的xml文件删除,然后添加下面这个类:
通过springboot强大的autoConfiguration进行自动配置:
package org.getty.home.configuration;
import java.util.Properties;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ExecutorType;
import org.getty.plugin.mybatis.interceptor.DateTimeInterceptor;
import org.getty.plugin.mybatis.interceptor.PrintSqlInterceptor;
import org.springframework.context.annotation.Bean;
import com.github.pagehelper.PageInterceptor;
@org.springframework.context.annotation.Configuration
public class MyBatisConfig
{
@Bean
public Configuration mybatisConfiguration()
{
Configuration configuration = new Configuration();
// 全局映射器启用缓存
configuration.setCacheEnabled(false);
// 查询时,关闭关联对象即时加载以提高性能
configuration.setLazyLoadingEnabled(false);
// 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果
configuration.setMultipleResultSetsEnabled(true);
// 允许使用列标签代替列名
configuration.setUseColumnLabel(true);
// 给予被嵌套的resultMap以字段-属性的映射支持 FULL,PARTIAL
configuration.setAutoMappingBehavior(AutoMappingBehavior.PARTIAL);
// 对于批量更新操作缓存SQL以提高性能 BATCH,SIMPLE,设置为BATCH有个缺陷就是无法获取update、delete返回的行数
configuration.setDefaultExecutorType(ExecutorType.SIMPLE);
// 允许在嵌套语句上使用行边界。如果允许,设置false。
configuration.setSafeRowBoundsEnabled(false);
// 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能
configuration.setAggressiveLazyLoading(false);
// 数据库超过30秒仍未响应则超时
configuration.setDefaultStatementTimeout(30);
//驼峰命名,如果不进行配置,数据库中有下划线的字段是不可以转换成驼峰命名的
configuration.setMapUnderscoreToCamelCase(true);
// 添加分页拦截器
//configuration.addInterceptor(pageInterceptor());
// 添加时间注解拦截器
//configuration.addInterceptor(dateTimeInterceptor());
// 打印sql拦截器
//configuration.addInterceptor(printSqlInterceptor());
return configuration;
}
//以下是配置mybatis的拦截器,可以按需添加。部分拦截器实现在博客里可以找到
@Bean
public PageInterceptor pageInterceptor()
{
//配合PageHelpder使用
Properties properties = new Properties();
properties.setProperty("helperDialect", "mysql");
// 设置为true时,会将RowBounds第一个参数offset当成pageNum页码使用 ,
// 和startPage中的pageNum效果一样
properties.setProperty("offsetAsPageNum", "false");
// 设置为true时,使用RowBounds分页会进行count查询
properties.setProperty("rowBoundsWithCount", "true");
// 设置为true时,如果pageSize=0或者RowBounds.limit = 0就会查询出全部的结果
properties.setProperty("pageSizeZero", "true");
// 启用合理化时,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页,禁用合理化时,如果pageNum<1或pageNum>pages会返回空数据
properties.setProperty("reasonable", "false");
PageInterceptor pi = new PageInterceptor();
pi.setProperties(properties);
return pi;
}
@Bean
public DateTimeInterceptor dateTimeInterceptor()
{
return new DateTimeInterceptor();
}
@Bean
public PrintSqlInterceptor printSqlInterceptor()
{
return new PrintSqlInterceptor();
}
}
把这个类添加到工程中,基本就配置好了。
最后需要把这个mybatisConfiguration注册到你的SqlSessionFactory里面。
下面提供一个数据库的代码配置类:
/*
* 文件名:DbConfig.java 版权:Copyright by www.poly.com 描述: 修改人:gogym 修改时间:2019年3月4日 跟踪单号: 修改单号: 修改内容:
*/
package org.getty.home.configuration;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.getty.plugin.dynamicsource.DatabaseType;
import org.getty.plugin.dynamicsource.DynamicDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import com.zaxxer.hikari.HikariDataSource;
@Configuration
public class DbConfig {
@Autowired
private Environment env;
@Autowired
private org.apache.ibatis.session.Configuration mybatisConfiguration;//mybatis配置类
/**
* 创建数据源(数据源的名称:方法名可以取为XXXDataSource(),XXX为数据库名称,该名称也就是数据源的名称)
*/
private DataSource dataSource() throws Exception {
HikariDataSource ds = new HikariDataSource();
ds.setJdbcUrl(env.getProperty("spring.datasource.url"));
ds.setUsername(env.getProperty("spring.datasource.username"));
ds.setPassword(env.getProperty("spring.datasource.password"));
ds.setDriverClassName(env
.getProperty("spring.datasource.driverClassName"));
return ds;
}
/**
* @throws Exception
* @Primary 该注解表示在同一个接口有多个实现类可以注入的时候,默认选择哪一个,而不是让@autowire注解报错
* @Qualifier 根据名称进行注入,通常是在具有相同的多个类型的实例的一个注入(例如有多个DataSource类型的实例)
*/
@Bean("dynamicDataSource")
@Primary
public DynamicDataSource dynamicDataSource() throws Exception {
DataSource dataSource = dataSource();
// 可以添加多个数据源,如果需要的话
Map<Object, Object> targetDataSources = new HashMap<>();
targetDataSources.put(DatabaseType.DEFAULT, dataSource);
DynamicDataSource dynamicDataSource = new DynamicDataSource();
dynamicDataSource.setTargetDataSources(targetDataSources);// 该方法是AbstractRoutingDataSource的方法
dynamicDataSource.setDefaultTargetDataSource(dataSource);// 默认的datasource设置为myTestDbDataSource
return dynamicDataSource;
}
@Bean
public SqlSessionFactory sqlSessionFactory(
@Qualifier("dynamicDataSource") DynamicDataSource dynamicDataSource)
throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
/** 设置datasource */
sessionFactory.setDataSource(dynamicDataSource);
//注册到事务工厂
sessionFactory.setConfiguration(mybatisConfiguration);
/** 设置typeAlias 包扫描路径,使用自定义数据源,该配置无效 */
// sessionFactory.setTypeAliasesPackage("com.rbl.log.module.dao");
/** 添加mapper 扫描路径 */
sessionFactory
.setMapperLocations(new PathMatchingResourcePatternResolver()
.getResources("classpath:mapper/**/*.xml"));
return sessionFactory.getObject();
}
/**
* 配置事务管理器
*/
@Bean
public DataSourceTransactionManager transactionManager(
DynamicDataSource dynamicDataSource) throws Exception {
return new DataSourceTransactionManager(dynamicDataSource);
}
}
完