我有两个表之间的父/子关系,以及我的 Java 类中的相应映射。表格大致如下:
A (ref number, stuff varchar2(4000))
B (a_ref number, other number, foo varchar2(200))
和 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;
}
这很好用,但我想对从子表中检索到的行添加一个过滤器。生成的查询如下所示:
select a_ref, other, foo from B where a_ref = ?
我希望它是:
select a_ref, other, foo from B where a_ref = ? and other = 123
附加过滤器将只是一个列名和一个硬编码值。有没有办法使用 hibernate 注释来做到这一点?
我查看了 @JoinFormula
,但我总是必须从父表中引用列名(在 JoinFormula 的 name
属性中)。
提前感谢您的任何建议。
最佳答案
JPA 不支持,但是如果你使用 hibernate 作为 JPA 提供者,那么你可以使用注解 @FilterDef
和 @Filter
。
Hibernate Core Reference Documentation
Hibernate3 has the ability to pre-define filter criteria and attach those filters at both a class level and a collection level. A filter criteria allows you to define a restriction clause similar to the existing "where" attribute available on the class and various collection elements. These filter conditions, however, can be parameterized. The application can then decide at runtime whether certain filters should be enabled and what their parameter values should be. Filters can be used like database views, but they are parameterized inside the application.
示例
@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
关于java - 用于过滤 @OneToMany 关联结果的注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6919686/