hibernate过滤器 filters
过滤器条件相当于一个非常类似于类和各种集合上的 where 属性的约束子句;
用法
1.在实体类上增加注解@FilterDef和@Filter
@Entity
@Table(name = "cloud_account")
@Data
@Accessors(chain = true)
@NoArgsConstructor
@AllArgsConstructor
@Builder
@DynamicInsert
@DynamicUpdate
//cuserFilter 是自定义的属性名,可以根据这个属性名找到该实体类
//userId也是自定义的属性名,用于获取属性值,type就是声明类型
@FilterDef(name = "cuserFilter", parameters = @ParamDef(name = "userId", type = "int"))
//cuserFilter 是自定义的属性名,status就是该实体类对应表的字段名,:userId就是获取userId的值,该值可以是集合,可以是基本类型
//@Filter(name = "cuserFilter", condition = "status = (:userId)")
@Filter(name = "cuserFilter", condition = "status in (:userId)")
public class CloudAccount {
private String account;
private String status;
}
2.设置filter的值
一般都是自定义注解,在切面中设置值的
//EntityManager是JPA中用于增删改查的接口,它的作用相当于一座桥梁,连接内存中的java对象和数据库的数据存储。
//1
@PersistenceContext
private EntityManager entityManager;
@Around("@annotation(dataFilter)")
public Object doProcess(ProceedingJoinPoint joinPoint, DataFilter dataFilter) {
List<Integer> towerIdList = new ArrayList<>();
//固定写法
//2
Session session = entityManager.unwrap(Session.class);
//自定义的属性名
//3
Filter filter = session.enableFilter("windTowerFilter");
//自定义属性值名,设置值,该值可以是集合类型,可以是基本类型,这里是集合类型
filter.setParameterList("towerIds", towerIdList);
}
补充:实体类可以设置多个Filter
使用:@FilterDefs , @Filters
例:
@EntityListeners({AuditingEntityListener.class, CusernameJpaListener.class})
@FilterDefs({@FilterDef(name = "cuserFilter", parameters = @ParamDef(name = "userId", type = "int")),
@FilterDef(name = "windTowerFilter", parameters = @ParamDef(name = "towerIds", type = "int")),
@FilterDef(name = "level2CompanyIdFilter", parameters = @ParamDef(name = "companyId", type = "int"))})
@Filters({@Filter(name = "cuserFilter", condition = "cuser = (:userId)"),
@Filter(name = "windTowerFilter", condition = "id in (:towerIds)"),
@Filter(name = "level2CompanyIdFilter", condition = "level2_company_id = (:companyId)")})
@Entity
@Table(name = "tbl_wind_tower")
public class WindTower implements Serializable {
}