spring切面过滤器--逻辑删除

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;
}

总结

这就是给逻辑删除增加切面的方法,一个切面类,两行注解,搞定。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值