文章目录
1. MyBatis 中#{}和${}的区别
#{}
: 解析为一个 JDBC 预编译语句(PreparedStatement )的参数标记符,一个 #{ } 代表一个占位符 ,可预防大部分 SQL 注入${}
: 纯粹的 String 拼接,在动态 SQL 解析阶段将会进行变量替换,当需要传入表名或者按照列排序时可使用
2. MyBatis-plus 的字段非 null 更新
使用 Mapper 通过 bean 对象更新数据库记录的时候,字段更新的策略会影响更新的结果,mybatis-plus的字段默认策略是 FieldStrategy.NOT_NULL
。该特性可在数据库表映射生成的 bean 的属性上通过以下注解使用
@TableField(value = "FstrLoanOrder",updateStrategy = FieldStrategy.NOT_EMPTY)
private String loanOrder;
public class GlobalConfig implements Serializable {
......
/**
* 字段验证策略之 insert
*
* @since 3.1.2
*/
private FieldStrategy insertStrategy = FieldStrategy.NOT_NULL;
/**
* 字段验证策略之 update
*
* @since 3.1.2
*/
private FieldStrategy updateStrategy = FieldStrategy.NOT_NULL;
/**
* 字段验证策略之 select
*
* @since 3.1.2
*/
private FieldStrategy selectStrategy = FieldStrategy.NOT_NULL;
}
}
public enum FieldStrategy {
/**
* 忽略判断
*/
IGNORED,
/**
* 非NULL判断, bean 对象属性为 NULL 则不更新对应表字段
*/
NOT_NULL,
/**
* 非空判断(只对字符串类型字段,其他类型字段依然为非NULL判断)
*/
NOT_EMPTY,
/**
* 默认的,一般只用于注解里
* <p>1. 在全局里代表 NOT_NULL</p>
* <p>2. 在注解里代表 跟随全局</p>
*/
DEFAULT,
/**
* 不加入 SQL
*/
NEVER
}
3. MyBatis-plus 使用技巧
3.1 自定义 sql 使用条件构造器作为参数
MyBatis-plus
中使用 @Select
等注解自定义了部分 SQL 语句,同时想使用其条件构造器时,只需要将构造器入参用@Param(Constants.WRAPPER)
修饰,再在自定义语句中添加 ${ew.customSqlSegment}
占位即可
@Select("select FuiQuota from fund.t_fund_quota ${ew.customSqlSegment}")
Long queryQuota(@Param(Constants.WRAPPER) LambdaQueryWrapper<FundQuota> queryWrapper);
3.2 inSql 子查询
通常在代码中都是简单查询,但是在完成某些比较奇葩的需求时可能需要用到嵌套子查询,MyBatis-plus
为此在查询构造器中提供了 inSql()
方法
LambdaQueryWrapper<Request> wrapper = Wrappers.<MatchRequest>lambdaQuery().inSql(Request::getId, insql)
3.3 and / or / nested 语句嵌套
有些复杂的查询会用到嵌套语句,也就是包裹在括号中的语句,来表示一种条件的并列。这种场景需要动态拼接 SQL 语句,一个示例如下:OR 嵌套中存在两个 AND 连接的条件,可表示语句 OR (FuiProductId = ? AND FuiTradeId IN (?, ?))
。如果 or()
方法不传入任何参数,则属于外层普通的 OR 连接符号
wrapper.or(orWrapper -> {
orWrapper.eq(Target::getProductId, item.getProductId());
if (!CollectionUtils.isEmpty(item.getTradeIds())) {
orWrapper.in(Target::getTradeId, item.getTradeIds());
}
}
3.4 读写分离
整合 dynamic-datasource-spring-boot-starter 可以方便地使用 @DS
注解实现数据源切换,写入时在Mapper
方法上使用@DS("master")
切换主库,读取则使用@DS("slave")
切换从库即可
spring:
datasource:
dynamic:
# 默认的数据源或者数据源组
primary: master
datasource:
# 主库名称 master
master:
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
# 重点配置,主库所在服务器 url
url: jdbc:mysql://xx.xx.xx.xx:3306/request?characterEncoding=utf8&useSSL=false
druid: # 以下参数针对每个库可以重新设置druid参数
initial-size:
validation-query: select 1 FROM DUAL #比如oracle就需要重新设置这个
# 从库名称 slave
slave:
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
# 重点配置,从库所在服务器 url
url: jdbc:mysql://xx.xx.xx.xx:3306/request?characterEncoding=utf8&useSSL=false
druid: # 以下参数针对每个库可以重新设置druid参数
initial-size:
validation-query: select 1 FROM DUAL