用于过滤@OneToMany关联结果的注释

Xav*_*ier 20 java hibernate jpa jointable

我有两个表之间的父/子关系,以及我的Java类中的相应映射.表大致如下:

A (ref number, stuff varchar2(4000))
B (a_ref number, other number, foo varchar2(200))
Run Code Online (Sandbox Code Playgroud)

和Java代码:

@Entity
class A {
    @Id
    @Column(name = "REF")
    private int ref;

    @OneToMany
    @JoinColumn(name = "A_REF", referencedName = "REF")
    private Set<B> bs;
}

@Entity
class B {
    @Id
    @Column(name = "A_REF")
    private int aRef;

    @Id
    @Column(name = "OTHER")
    private int other;
}
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我想在从子表中检索的行上添加一个过滤器.生成的查询如下所示:

select a_ref, other, foo from B where a_ref = ?
Run Code Online (Sandbox Code Playgroud)

我希望它是:

select a_ref, other, foo from B where a_ref = ? and other = 123
Run Code Online (Sandbox Code Playgroud)

附加过滤器只是列名和硬编码值.有没有办法使用hibernate注释来做到这一点?

我看过了@JoinFormula,但是我总是要从父表中引用一个列名(在nameJoinFormula 的属性中).

提前感谢任何建议.

Joe*_*don 28

JPA不支持它,但如果您使用hibernate作为JPA提供程序,那么您可以使用注释@FilterDef@Filter.

Hibernate核心参考文档

Hibernate3能够预先定义过滤条件,并在类级别和集合级别附加这些过滤器.过滤条件允许您定义类似于类和现有"where"属性的限制子句以及各种集合元素.但是,可以参数化这些过滤条件.然后,应用程序可以在运行时决定是否应启用某些过滤器以及它们的参数值应该是什么.过滤器可以像数据库视图一样使用,但它们在应用程序内部进行参数化.

为例

@Entity
public class A implements Serializable{
    @Id
    @Column(name = "REF")
    private int ref;

    @OneToMany
    @JoinColumn(name = "A_REF", referencedColumnName = "REF")   
    @Filter(name="test")
    private Set<B> bs;
}

@Entity
@FilterDef(name="test", defaultCondition="other = 123")
public class B implements Serializable{
    @Id
    @Column(name = "A_REF")
    private int aRef;

    @Id
    @Column(name = "OTHER")
    private int other;
}

Session session = entityManager.unwrap(Session.class);
session.enableFilter("test");
A a = entityManager.find(A.class, new Integer(0))
a.getb().size() //Only contains b that are equals to 123
Run Code Online (Sandbox Code Playgroud)


Uri*_*oya 6

另一个解决方案是使用Hibernate的@Where:https ://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#pc-where

    @OneToMany
    @JoinColumn(name = "A_REF", referencedName = "REF")
    @Where(clause = "other = 123")
    private Set<B> bs;
Run Code Online (Sandbox Code Playgroud)