origin
Today we plan to use in the new project in Mybatis Plus
the 3.x
version, and then found that 2.x
version was scrapped in some configurations. One field-strategy
attracted attention.
Sometimes lazy line may cause problems, it still looks.
text
In MP
, this setting will affect the sql
splicing behavior statement. In the 2.x
release, this is not distinguish individual policy fields can not be set.
Differences are explained below by specific configuration
# 2.x配置
mybatis-plus:
mapper-locations:
- classpath*:mapper/**/*Mapper.xml
typeAliasesPackage: com.test.assist.dao.domain
global-config:
id-type: 0
field-strategy: 2
db-column-underline: true
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
#3.x的配置
mybatis-plus:
typeAliasesPackage: com.test.assist.dao.domain
mapper-locations:
- classpath*:mapper/**/*Mapper.xml
global-config:
db-config:
select-strategy: not_empty
insert-strategy: not_empty
update-strategy: not_empty
id-type: auto
configuration:
map-underscore-to-camel-case: true
cache-enabled: false
public enum FieldStrategy {
IGNORED,
NOT_NULL,
NOT_EMPTY,
DEFAULT,
NEVER;
private FieldStrategy() {
}
}
Through access to information and look at the source code and found that this field will mainly affect sql
splicing. We know that when by Entity
the time update the table will be updated only non-empty fields. For those who value NULL
field will not appear in the sql
sentence inside.
Now I intercepted some source code from inside
protected String convertIfTag(boolean ignored, TableFieldInfo fieldInfo, String prefix, boolean close) {
FieldStrategy fieldStrategy = fieldInfo.getFieldStrategy();
//如果字段策略为忽略,进行相应的处理
if (fieldStrategy == FieldStrategy.IGNORED) {
if (ignored) {
return "";
}
fieldStrategy = this.getGlobalConfig().getFieldStrategy();
}
if (close) {
return "</if>";
} else {
String property = fieldInfo.getProperty();
Class propertyType = fieldInfo.getPropertyType();
property = StringUtils.removeIsPrefixIfBoolean(property, propertyType);
if (null != prefix) {
property = prefix + property;
}
//重点是这里,如果字段策略为NOT_EMPTY,那么会对当前字段的值进行判断
if (fieldStrategy == FieldStrategy.NOT_EMPTY) {
return StringUtils.isCharSequence(propertyType) ? String.format("\n\t<if test=\"%s!=null and %s!=''\">", property, property) : String.format("\n\t<if test=\"%s!=null \">", property);
} else {
return String.format("\n\t<if test=\"%s!=null\">", property);
}
}
}
It can be concluded from the above code:
- NOT_EMPTY: will be null and the field value 'comparison operation
- NOT_NULL: will be null checks
At the same time in 3.x
release, support for select
, update
, insert
set a different field tactics, it is apparent to everyone across the board this behavior is quite objectionable. This, I also see in GitHub issue
.
to sum up
For unclear configuration can not gulping, otherwise easily lead to disaster.
references
- github issue
- MyBatis-Plus Properties Detailed configuration of field-strategy
- MP 2.x document
- MP 3.x Documentation