Let’s say those are my entities:
Table1.java
@Entity
public class Table1 {
// Many to one
private Table2 table2;
// Raw attributes
// ...
}
Table2.java
@Entity
public class Table2 {
// Many to one
private Table3 table3;
// Raw attributes
// ...
}
Table3.java
@Entity
public class Table3 {
// Raw attributes
private String lang; // "fr", "en", "de"...
}
When I wanna list all of the Table1 rows whose property table2.table3.lang equals en, I’m doing like this:
Query query = entityManager.createQuery("SELECT t1 FROM Table1 t1 WHERE t1.table2.table3.lang = :lang");
query.setParameter("lang", "en");
That said, how can I execute that query on a previously populated Iterable<Table1>? Is it only feasible? If not with Hibernate, then with what? For example, even if I know the code below doesn’t work, something like:
Set<Table1> set = new HashSet<Table1>();
set.add(new Table1(INIT_DEFAULT_VALUES));
set.add(new Table2(INIT_DEFAULT_VALUES));
set.add(new Table3(INIT_DEFAULT_VALUES));
Query query = entityManager.createQuery("SELECT t1 FROM :set t1 WHERE t1.table2.table3.lang = :lang");
query.setParameter("set", set);
query.setParameter("lang", "en");
For those who wonder why do I need such a stuff, I’m using Apache Lucene to perform the users’ searches within the Table1 rows, previously indexed by Lucene too. Once I get some results, I have to propose some filters/sorts on the returned list, e.g. choosing the lang of the linked Table3 entity.
Any suggestion would be appreciated :)
Hibernate queries are translated into SQL queries and executed in the database. If the set contains entity instances that are not into the database, there’s no way Hibernate can query them.
If these entities are in fact entities from the database, as you seem to indicate, then you might just use an
INclause:But make sure you don’t have too many IDs and you don’t hit the limit imposed by your database (Oracle limits elements of an IN clause to 1000 for example).
If those entities are already loaded in memory, you could also just iterate through them: