2

我想知道是否可以使用 JPA 注释配置动态 @where 子句。假设我在两个类之间有关系——公司(父)和调用(子)。

如果有这样的注释声明(伪代码)。

@ManyToOne
@JoinColumn(name = "ID_MEN_PRE", referencedColumnName = "ID_MEN"
@Where(clause="invoice_month=:month")
private Testinvoices invoice;

我现在想做的是在 where 子句中传递“月”值。结果应仅返回给定日期的 Testinvoices。

有没有办法做到这一点?

4

3 回答 3

3

不可以,但是过滤器 - 见下文 - 可以参数化。

但是,在我看来,您正在尝试对关系进行建模,而实际上查询将是更好的解决方案。

或者,在数据库级别创建按日期过滤的视图,并将发票映射到该视图而不是表。

17.1. 休眠过滤器

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

于 2013-10-15T15:27:42.140 回答
1
This is not possible in JPA.

For same effect you can use criteria. Please refer to example below

Criteria criteria = session.createCriteria(Employees.class);

if (subsidiaryId != null) {
  criteria.add(Restrictions.eq("subsidiaryId", subsidiaryId));
}
if (employeeId != null) {
  criteria.add(Restrictions.eq("employeeId", employeeId));
}
if (lastName != null) {
  criteria.add(
    Restrictions.eq("lastName", lastName).ignoreCase()
  );
}
于 2013-10-15T09:34:49.027 回答
1

在运行时无法传递参数,但可以像这样使用它

@ManyToOne
@JoinColumn(name = "ID_MEN_PRE", referencedColumnName = "ID_MEN"
@Where(clause="invoice_month=january")
private Testinvoices invoice;
于 2013-10-18T20:44:21.440 回答