Hibernate: queries by example and many-to-one relationships

7.1k views Asked by At

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"...

}

I wanna list all the Table1 rows that have a table2.table3.lang that equals en. I tried to use a query by example:

Table3 table3Example = new Table3();
table3Example.setLang("en");

Table2 table2Example = new Table2();
table2Example.setTable3(table3Example);

Table1 table1Example = new Table1();
table1Example.setTable2(table2Example);

table1Repository.findByExample(table1Example);

The problem is that .findByExample(table1Example) returns all the rows of the database, no matter of the lang, which means that the filter isn't considered at all :(

Any help would be appreciated :)

PS: no exception is thrown, .findByExample(table1Example) just returns all of the Table1 rows.

1

There are 1 answers

3
tibtof On BEST ANSWER

Try something like this:

    Query q = entityManager.createQuery("Select o from Table1 o where o.table2.table3.lang = :lang");
    q.setParameter("lang", "en");
    List<Table1> r = (List<Table1>)q.getResultList();

To see why you get all the rows in Table1, make sure that you have

<property name="hibernate.show_sql" value="true"/>

in your persistence.xml and then watch the log to see the actual select that hibernate executes.