我有2个@Where注释实体。第一个是Category;
@Where(clause = "DELETED = '0'")
public class Category extends AbstractEntity
它有以下关系;
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "category")
private Set<SubCategory> subCategories = Sets.newHashSet();
,第二个实体是SubCategory;
@Where(clause = "DELETED = '0'")
public class SubCategory extends AbstractEntity
并包含相应的关系;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "CATEGORY_ID")
private Category category;
每当我调用以下Dao方法时;
@Query(value = "select distinct category from Category category join fetch category.subCategories subcategories")
public List<Category> findAllCategories();
我得到了以下sql查询;
select
distinct category0_.id as id1_3_0_,
subcategor1_.id as id1_16_1_,
category0_.create_time as create2_3_0_,
category0_.create_user as create3_3_0_,
category0_.create_userip as create4_3_0_,
category0_.deleted as deleted5_3_0_,
category0_.update_time as update6_3_0_,
category0_.update_user as update7_3_0_,
category0_.update_userip as update8_3_0_,
category0_.version as version9_3_0_,
category0_.name as name10_3_0_,
subcategor1_.create_time as create2_16_1_,
subcategor1_.create_user as create3_16_1_,
subcategor1_.create_userip as create4_16_1_,
subcategor1_.deleted as deleted5_16_1_,
subcategor1_.update_time as update6_16_1_,
subcategor1_.update_user as update7_16_1_,
subcategor1_.update_userip as update8_16_1_,
subcategor1_.version as version9_16_1_,
subcategor1_.category_id as categor11_16_1_,
subcategor1_.name as name10_16_1_,
subcategor1_.category_id as categor11_3_0__,
subcategor1_.id as id1_16_0__
from
PUBLIC.t_category category0_
inner join
PUBLIC.t_sub_category subcategor1_
on category0_.id=subcategor1_.category_id
where
(
category0_.DELETED = '0'
)
你能告诉我为什么上面的查询缺乏
和subcategor1_.DELETED ='0'
在哪里阻止?
答案 0 :(得分:6)
我刚刚解决了项目中的类似问题。
可以将@Where注释不仅放在Entity上,还可以放在子集上。
根据javadoc:
要添加到元素的Where子句实体或目标集合的实体
在你的情况下,它会像:
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "category")
@Where(clause = "DELETED = '0'")
private Set<SubCategory> subCategories = Sets.newHashSet();
请查找已解决的类似问题here
我认为因此,与使用Hibernate过滤器相比,解决方案不具有侵入性。默认情况下,这些过滤器处于禁用状态并在会话级别运行,因此每次新的Session打开时启用它们都是额外的工作,尤其是当您的DAO通过Spring Data等抽象工作时
答案 1 :(得分:0)
这是一个快速回复;
@Where(clause = "DELETED = '0'")
public class SubCategory extends AbstractEntity
直接查询SubCategry时, Where
会生效。
要不删除子类别,请使用Hibernate Filters
例如here