如果需要在查询时自动加上逻辑删除的条件,可以通过全局配置添加,我不想使用xml配置,想使用java显式配置
时间: 2023-12-04 22:01:51 浏览: 33
可以通过实现 MyBatis 的 Interceptor 接口来实现在查询时自动加上逻辑删除的条件。具体步骤如下:
1. 创建一个类实现 Interceptor 接口,并重写其中的方法。
```java
public class LogicDeleteInterceptor implements Interceptor {
private final String deleteField = "is_deleted";
private final String deleteValue = "0";
@Override
public Object intercept(Invocation invocation) throws Throwable {
MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
Object parameter = invocation.getArgs()[1];
BoundSql boundSql = mappedStatement.getBoundSql(parameter);
String originalSql = boundSql.getSql();
String newSql = addLogicDeleteCondition(originalSql);
Field field = boundSql.getClass().getDeclaredField("sql");
field.setAccessible(true);
field.set(boundSql, newSql);
return invocation.proceed();
}
private String addLogicDeleteCondition(String originalSql) {
StringBuilder sb = new StringBuilder(originalSql);
int index = sb.indexOf("from");
sb.insert(index + 4, " " + deleteField + " = " + deleteValue + " and ");
return sb.toString();
}
@Override
public Object plugin(Object target) {
return Plugin.wrap(target, this);
}
@Override
public void setProperties(Properties properties) {
// do nothing
}
}
```
2. 在 MyBatis 的配置文件中添加该 Interceptor。
```java
@Configuration
@MapperScan("com.example.mapper")
public class MyBatisConfig {
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
// 添加自定义 Interceptor
sessionFactory.setPlugins(new LogicDeleteInterceptor());
return sessionFactory;
}
}
```
这样,在进行查询操作时,就会自动加上逻辑删除的条件,从而实现自动过滤已删除的数据。