我有一个实体 ParentEntity 定义为
public class ParentEntity
{
private long id;
private List<ChildEntity> children;
@OneToMany(mappedBy = "parent")
public List<ChildEntity> getChildren()
{
return children;
}
}
和
public class ChildEntity
{
private ParentEntity parent;
private String code;
...
}
我知道使用注释 @FilterJoinTable 我可以过滤 parent 有一个具有特定代码的 child ,定义为过滤器参数,但是 我试图弄清楚如何通过注释过滤没有 child 的 parent 或以代码作为参数定义的 child 。
类似 SQL 的东西:
select * from ParentEntity p left join ChildEntity c
on p.id=c.parent_id
where p.id in (select p.id from ParentEntity p join ChildEntity c
on p.id=c.parent_id where c.code=:code)
OR p.id not in ( select parent_id from ChildEntity )
或 HQL:
select p from ParentEntity p join fetch p.childen c
where p.id in (select p.id from ParentEntity p join p.childen c where c.code=:code)
OR p.id not in ( select c.parent.id from ChildEntity c )
这是因为我有很多 Parent
的类(class)或List<Parent>
作为属性(property),每个人都检索 ChildEntity
同样,始终具有与上述相同的条件,因此我不会在所有查询上重写相同的条件。
你有什么想法吗?
谢谢
最佳答案
过滤子句直接进入 SQL where 子句。
我认为你可以尝试这样的事情:
@Filter(name = "childWithCode",
condition = "(exists (select 1 from ChildEntity ce where id = ce.parent_id and code='foobar'))")
public class ParentEntity { ...
关于java - 我可以使用 Hibernate 过滤注释按子集合内容过滤实体吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27941516/