This article Source: GitHub · Click here || GitEE · Click here
I. Introduction Projects
1, multiple data Profile
Actual projects, often use different databases to meet the actual needs of the project. With the increasing amount of concurrent traffic, a project using multiple databases: master-slave replication, read and write separation, distributed databases, etc., it is becoming more common.
2, MybatisPlus Profile
MyBatis-Plus (abbreviated MP) is a MyBatis enhancement tools, enhanced not only change on the basis of MyBatis, to simplify development, increase efficiency and health.
Plug Features
无代码侵入:只做增强不做改变,引入它不会对现有工程产生影响。
强大的 CRUD 操作:通过少量配置即可实现单表大部分 CRUD 操作满足各类使用需求。
支持 Lambda 形式调用:通过 Lambda 表达式,方便的编写各类查询条件。
支持主键自动生成:可自由配置,解决主键问题。
内置代码生成器:采用代码或者 Maven 插件可快速生成各层代码。
内置分页插件:基于 MyBatis 物理分页,开发者无需关心具体操作。
内置性能分析插件:可输出 Sql 语句以及其执行时间。
Second, the case of multiple data sources
1, project structure
Note: mapper mapper.xml layer and layers were placed on a different directory for loading mybatis scan.
2, multi data source configuration
spring:
# 数据源配置
datasource:
type: com.alibaba.druid.pool.DruidDataSource
admin-data:
driverClassName: com.mysql.jdbc.Driver
dbUrl: jdbc:mysql://127.0.0.1:3306/cloud-admin-data?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false
username: root
password: 123
initialSize: 20
maxActive: 100
minIdle: 20
maxWait: 60000
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 30
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 30000
maxEvictableIdleTimeMillis: 60000
validationQuery: SELECT 1 FROM DUAL
testOnBorrow: false
testOnReturn: false
testWhileIdle: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
filters: stat,wall
user-data:
driverClassName: com.mysql.jdbc.Driver
dbUrl: jdbc:mysql://127.0.0.1:3306/cloud-user-data?useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false
username: root
password: 123
initialSize: 20
maxActive: 100
minIdle: 20
maxWait: 60000
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 30
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 30000
maxEvictableIdleTimeMillis: 60000
validationQuery: SELECT 1 FROM DUAL
testOnBorrow: false
testOnReturn: false
testWhileIdle: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
filters: stat,wall
Formal parameters here are diverse, only you need to configure the scanning parameters can be.
3, the scan parameters based
@Component
@ConfigurationProperties(prefix = "spring.datasource.admin-data")
public class DruidOneParam {
private String dbUrl;
private String username;
private String password;
private String driverClassName;
private int initialSize;
private int maxActive;
private int minIdle;
private int maxWait;
private boolean poolPreparedStatements;
private int maxPoolPreparedStatementPerConnectionSize;
private int timeBetweenEvictionRunsMillis;
private int minEvictableIdleTimeMillis;
private int maxEvictableIdleTimeMillis;
private String validationQuery;
private boolean testWhileIdle;
private boolean testOnBorrow;
private boolean testOnReturn;
private String filters;
private String connectionProperties;
// 省略 GET 和 SET
}
4, the connection pool configuration Druid
@Configuration
@MapperScan(basePackages = {"com.data.source.mapper.one"},sqlSessionTemplateRef = "sqlSessionTemplateOne")
public class DruidOneConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(DruidOneConfig.class) ;
@Resource
private DruidOneParam druidOneParam ;
@Bean("dataSourceOne")
public DataSource dataSourceOne () {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(druidOneParam.getDbUrl());
datasource.setUsername(druidOneParam.getUsername());
datasource.setPassword(druidOneParam.getPassword());
datasource.setDriverClassName(druidOneParam.getDriverClassName());
datasource.setInitialSize(druidOneParam.getInitialSize());
datasource.setMinIdle(druidOneParam.getMinIdle());
datasource.setMaxActive(druidOneParam.getMaxActive());
datasource.setMaxWait(druidOneParam.getMaxWait());
datasource.setTimeBetweenEvictionRunsMillis(druidOneParam.getTimeBetweenEvictionRunsMillis());
datasource.setMinEvictableIdleTimeMillis(druidOneParam.getMinEvictableIdleTimeMillis());
datasource.setMaxEvictableIdleTimeMillis(druidOneParam.getMaxEvictableIdleTimeMillis());
datasource.setValidationQuery(druidOneParam.getValidationQuery());
datasource.setTestWhileIdle(druidOneParam.isTestWhileIdle());
datasource.setTestOnBorrow(druidOneParam.isTestOnBorrow());
datasource.setTestOnReturn(druidOneParam.isTestOnReturn());
datasource.setPoolPreparedStatements(druidOneParam.isPoolPreparedStatements());
datasource.setMaxPoolPreparedStatementPerConnectionSize(druidOneParam.getMaxPoolPreparedStatementPerConnectionSize());
try {
datasource.setFilters(druidOneParam.getFilters());
} catch (Exception e) {
LOGGER.error("druid configuration initialization filter", e);
}
datasource.setConnectionProperties(druidOneParam.getConnectionProperties());
return datasource;
}
@Bean
public SqlSessionFactory sqlSessionFactoryOne() throws Exception{
SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
factory.setDataSource(dataSourceOne());
factory.setMapperLocations(resolver.getResources("classpath*:/dataOneMapper/*.xml"));
return factory.getObject();
}
@Bean(name="transactionManagerOne")
public DataSourceTransactionManager transactionManagerOne(){
return new DataSourceTransactionManager(dataSourceOne());
}
@Bean(name = "sqlSessionTemplateOne")
public SqlSessionTemplate sqlSessionTemplateOne() throws Exception {
return new SqlSessionTemplate(sqlSessionFactoryOne());
}
}
Precautions
- MapperScan disposed on the specified data source;
- SqlSessionFactory configuration Mapper.xml scan addresses;
- DataSourceTransactionManager configuration of the transaction data source;
- The same two data sources disposed techniques, not described herein;
5, operation case
- A data source: a simple query
@Service public class AdminUserServiceImpl implements AdminUserService { @Resource private AdminUserMapper adminUserMapper ; @Override public AdminUser selectByPrimaryKey (Integer id) { return adminUserMapper.selectByPrimaryKey(id) ; } }
- Two data sources: transaction handling
@Service public class UserBaseServiceImpl implements UserBaseService { @Resource private UserBaseMapper userBaseMapper ; @Override public UserBase selectByPrimaryKey(Integer id) { return userBaseMapper.selectByPrimaryKey(id); } // 使用指定数据源的事务 @Transactional(value = "transactionManagerTwo") @Override public void insert(UserBase record) { // 这里数据写入失败 userBaseMapper.insert(record) ; // int i = 1/0 ; } }
Note: This requires you to specify the transaction manager of the data source configuration.
Three, MybatisPlus Case
1, dependent on the core
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.7.1</version>
<exclusions>
<exclusion>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus</artifactId>
<version>3.0.7.1</version>
</dependency>
2, the configuration file
mybatis-plus:
mapper-locations: classpath*:/mapper/*.xml
typeAliasesPackage: com.digital.market.*.entity
global-config:
db-config:
id-type: AUTO
field-strategy: NOT_NULL
logic-delete-value: -1
logic-not-delete-value: 0
banner: false
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true
cache-enabled: false
call-setters-on-nulls: true
jdbc-type-for-null: 'null'
3, hierarchical configuration
mapper层
UserBaseMapper extends BaseMapper<UserBase>
实现层
UserBaseServiceImpl extends ServiceImpl<UserBaseMapper,UserBase> implements UserBaseService
接口层
UserBaseService extends IService<UserBase>
4, mapper.xml file
<mapper namespace="com.plus.batis.mapper.UserBaseMapper" >
<resultMap id="BaseResultMap" type="com.plus.batis.entity.UserBase" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="pass_word" property="passWord" jdbcType="VARCHAR" />
<result column="phone" property="phone" jdbcType="VARCHAR" />
<result column="email" property="email" jdbcType="VARCHAR" />
<result column="create_time" property="createTime" jdbcType="TIMESTAMP" />
<result column="update_time" property="updateTime" jdbcType="TIMESTAMP" />
<result column="state" property="state" jdbcType="INTEGER" />
</resultMap>
<sql id="Base_Column_List" >
id, user_name, pass_word, phone, email, create_time, update_time, state
</sql>
<select id="selectByParam" parameterType="com.plus.batis.entity.QueryParam" resultMap="BaseResultMap">
select * from hc_user_base
</select>
</mapper>
Precautions
The method BaseMapper been the default implementation; this method can also be some of their own custom implementations.
5, the interface demo
@RestController
@RequestMapping("/user")
public class UserBaseController {
private static final Logger LOGGER = LoggerFactory.getLogger(UserBaseController.class) ;
@Resource
private UserBaseService userBaseService ;
@RequestMapping("/info")
public UserBase getUserBase (){
return userBaseService.getById(1) ;
}
@RequestMapping("/queryInfo")
public String queryInfo (){
UserBase userBase1 = userBaseService.getOne(new QueryWrapper<UserBase>().orderByDesc("create_time")) ;
LOGGER.info("倒叙取值:{}",userBase1.getUserName());
Integer count = userBaseService.count() ;
LOGGER.info("查询总数:{}",count);
UserBase userBase2 = new UserBase() ;
userBase2.setId(1);
userBase2.setUserName("spring");
boolean resFlag = userBaseService.saveOrUpdate(userBase2) ;
LOGGER.info("保存更新:{}",resFlag);
Map<String, Object> listByMap = new HashMap<>() ;
listByMap.put("state","0") ;
Collection<UserBase> listMap = userBaseService.listByMap(listByMap) ;
LOGGER.info("ListByMap查询:{}",listMap);
boolean removeFlag = userBaseService.removeById(3) ;
LOGGER.info("删除数据:{}",removeFlag);
return "success" ;
}
@RequestMapping("/queryPage")
public IPage<UserBase> queryPage (){
QueryParam param = new QueryParam() ;
param.setPage(1);
param.setPageSize(10);
param.setUserName("cicada");
param.setState(0);
return userBaseService.queryPage(param) ;
}
@RequestMapping("/pageHelper")
public PageInfo<UserBase> pageHelper (){
return userBaseService.pageHelper(new QueryParam()) ;
}
}
Here pageHelper method is to use a custom plug-PageHelper.
Fourth, the source address
GitHub·地址
https://github.com/cicadasmile/middle-ware-parent
GitEE·地址
https://gitee.com/cicadasmile/middle-ware-parent