spring切面过滤器工具类
需求描述:domain中增加【是否删除】isDelete属性。
项目背景:springmvc+jpa(springboot+jpa也试用)
方法:使用spring切面拦截,自动给该domain的查询方法,都加上是否删除为否。
备注:如果是表连接的查询方式,还是要手动修改一些sql或者jpa或者hql语句。
前言
这篇文章将提供一个逻辑删除的切面工具类,来过滤掉已经逻辑删除的数据。
使用步骤
1.引入库
pom.xml中加入依赖
2.过滤器
package com.xxx.framework.core;
import com.manager.domain.enumitem.IsFlag;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.hibernate.Session;
import org.hibernate.internal.FilterImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.persistence.EntityManager;
/**
* 行政区过滤器切面, 只适用于Query,不适用于direct fetching
*
*/
@Aspect
@Component
public class IsDeleteFilterAspect {
@Autowired
EntityManager em;
@Before("execution(* com.xxx..*.*Ctrl*.*(..))")
public void beforeQueryExecution(JoinPoint pjp) throws Throwable {
FilterImpl filter = (FilterImpl) em.unwrap(Session.class).enableFilter("is_delete_filter");
if (filter != null) {
try {
filter.setParameter("isDelete", IsFlag.NO.getKey());
filter.validate();
} catch (Exception e) {
}
}
}
}
3.使用方法
哪个domain要加逻辑删除,哪个就加上这两行注解
@FilterDef(name = “is_delete_filter”, parameters = @ParamDef(name = “isDelete”, type = “int”))
@Filter(name = “is_delete_filter”, condition = “is_delete_ = :isDelete”)
/**
* 行政区划
*
* @author sunyp
*/
@Entity
@Table(name = "smart_org")
@org.hibernate.annotations.Table(appliesTo = "smart_org", comment = "行政区划")
@TableGenerator(name = "com.xxx.manager.domain.Organization",
table = "PK_Sequence",
pkColumnName = "KEY_ID_",
valueColumnName = "GEN_VALUE_",
pkColumnValue = "com.xxx.manager.domain.Organization",
initialValue = 1,
allocationSize = 1
)
@Getter
@Setter
@EntityListeners({DataBaseTimeAuditListener.class})
@FilterDef(name = "is_delete_filter", parameters = @ParamDef(name = "isDelete", type = "int"))
@Filter(name = "is_delete_filter", condition = "is_delete_ = :isDelete")
public class Organization implements Serializable {
@Id
@Column(name = "id_", nullable = false, columnDefinition = "int comment '主键ID'")
@GeneratedValue(strategy = GenerationType.TABLE, generator = "com.manager.domain.Organization")
private Long id;
//行政区划编码
@Column(name = "code_", columnDefinition = "varchar(255) comment '行政区划编码'")
private String code;
// 是否删除
@Enumerated(EnumType.ORDINAL)
@Column(name = "is_delete_", length = 2, columnDefinition = "int comment '是否删除'")
private IsFlag isDelete;
}
总结
这就是给逻辑删除增加切面的方法,一个切面类,两行注解,搞定。

1299

被折叠的 条评论
为什么被折叠?



