公司里每条数据都有一个字段,这个字段在发布后才会添加上值,否则为null,而每次查询都要查询发布后的结果,但每个查询方法都要写!=null太麻烦,不知mybatisplus是否能进行全局配置,默认查询这个字段不为null的数据
找到mybatis-plus.configuration.sql-parser-cache改成false
在注解@TableField 有个whereStrategy 选择 FieldStrategy.NOT_NULL
针对你的问题,可以通过自定义MybatisPlus的插件进行全局配置,拦截SQL并添加查询参数,实现只查询非null的数据。
具体步骤如下:
public class NonNullInterceptor implements Interceptor {
@Override
public Object intercept(Invocation invocation) throws Throwable {
// 获取参数,修改SQL
Object[] args = invocation.getArgs();
MappedStatement mappedStatement = (MappedStatement) args[0];
Object parameter = args[1];
BoundSql boundSql = mappedStatement.getBoundSql(parameter);
String sql = boundSql.getSql();
// 在SQL中添加查询条件
sql += " WHERE field_name IS NOT NULL";
// 重新设置BoundSql中的SQL语句
BoundSql newBoundSql = new BoundSql(mappedStatement.getConfiguration(), sql,
boundSql.getParameterMappings(), boundSql.getParameterObject());
MappedStatement newMappedStatement = copyFromMappedStatement(mappedStatement, new BoundSqlSqlSource(newBoundSql));
args[0] = newMappedStatement;
return invocation.proceed();
}
private MappedStatement copyFromMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
Builder builder = new Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
builder.resource(ms.getResource());
builder.fetchSize(ms.getFetchSize());
builder.statementType(ms.getStatementType());
builder.keyGenerator(ms.getKeyGenerator());
builder.keyProperty(StringUtils.join(ms.getKeyProperties(), ","));
builder.timeout(ms.getTimeout());
builder.parameterMap(ms.getParameterMap());
builder.resultMaps(ms.getResultMaps());
builder.resultSetType(ms.getResultSetType());
return builder.build();
}
private static class BoundSqlSqlSource implements SqlSource {
private BoundSql boundSql;
public BoundSqlSqlSource(BoundSql boundSql) {
this.boundSql = boundSql;
}
@Override
public BoundSql getBoundSql(Object parameterObject) {
return boundSql;
}
}
}
@Configuration
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new NonNullInterceptor());
return interceptor;
}
}
@Mapper
@SqlParser(filter = true)
public interface UserMapper extends BaseMapper<User> {
List<User> selectUserList();
}
<select id="selectUserList" resultType="com.example.demo.entity.User">
SELECT * FROM user
</select>
通过以上步骤,你就可以实现在查询时自动添加查询条件,只查询非null的数据了。