Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.
preface
In CRUD business, it is inevitable to add and subtract columns. If mybatis- Plus is integrated in the project, there are only two solutions without any modification
- use
UpdateWrapper
Joining together - Write native SQL directly to XML
But neither method is elegant, because both require a long list of names. So I’ll try to implement a custom LambdaUpdateWrapper
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
Copy the code
Source code analysis
public LambdaUpdateWrapper<T> set(booleancondition, SFunction<T, ? > column, Object val) {
if (condition) {
sqlSet.add(String.format("%s=%s", columnToString(column), formatSql("{0}", val)));
}
return typedThis;
}
Copy the code
As you can see, it’s pretty easy to just convert SFunction to a database field name and concatenate strings, Set name = ‘new name’ (true, User::getName, ‘new name’)
We could also follow suit and inherit the LambdaUpdateWrapper directly
Code implementation
public class MyLambdaUpdateWrapper<T> extends LambdaUpdateWrapper<T> {
public MyLambdaUpdateWrapper(Class<T> entityClass) {
super(entityClass);
}
/** * specifies that the column is incremented *@paramColumns refer to *@paramValue Indicates the increment */
public MyLambdaUpdateWrapper<T> incrField(SFunction
columns, Object value)
,> {
String columnsToString = super.columnToString(columns);
String format = String.format("%s = %s + %s", columnsToString,columnsToString, formatSql("{0}", value));
setSql(format);
return this;
}
/** * specifies that the column is decrement from *@paramColumns refer to *@paramValue Decreases the value */
public MyLambdaUpdateWrapper<T> descField(SFunction
columns, Object value)
,> {
String columnsToString = super.columnToString(columns);
String format = String.format("%s = %s - %s", columnsToString,columnsToString, formatSql("{0}", value));
setSql(format);
return this; }}Copy the code
The code to call the service is as follows
MyLambdaUpdateWrapper<AgentInfo> updateWrapper = new MyLambdaUpdateWrapper(AgentInfo.class);
updateWrapper.incrField(AgentInfo::getRealBalance, amount);
updateWrapper.eq(AgentInfo::getId, agentId);
// Call update (..) of ServiceImpl.
return update(updateWrapper);
Copy the code