Reputation: 11310
I would like to know if it is possible to configure dynamic @where clauses with JPA anotations. Let's say I have a relationship between two classes - company (parent) and invoces (child).
If have a Annotation declaration like this (pseudo code).
@ManyToOne
@JoinColumn(name = "ID_MEN_PRE", referencedColumnName = "ID_MEN"
@Where(clause="invoice_month=:month")
private Testinvoices invoice;
What I would like to do now is to pass "month" value in the where clause. The result should return only Testinvoices by the given Date.
Is there a way how to do it?
Upvotes: 3
Views: 7483
Reputation: 11310
It is not possible to passe a parameter during the runtime but it is possible to use it like this way
@ManyToOne
@JoinColumn(name = "ID_MEN_PRE", referencedColumnName = "ID_MEN"
@Where(clause="invoice_month=january")
private Testinvoices invoice;
Upvotes: 2
Reputation: 23246
No, however Filters - see further below - can be parameterized.
However it looks to me like you are attempting to model a relationship when actually a query would be a better solution.
Or, create a view filtered by date at the database Level and map invoices to that view rather than a table.
17.1. Hibernate filters
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.
Upvotes: 3
Reputation: 8357
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()
);
}
Upvotes: 1