How to join Multiple tables using hibernate criteria where entity relationship is not direct?

seal picture seal · Jun 26, 2016 · Viewed 50.3k times · Source

I have three entities. those are:

@Entity
public class Organization {
    @Id
    private long id;
    @Column
    private String name;
}
@Entity
public class Book {
    @Id
    private Long id;
    @Column
    private String name;
    @ManyToOne
    private Organization organization;
}
@Entity
public class Account  {
   @Id
   private Long id;
   @Column
   private String name;
   @ManyToOne
   private Book book;
}

In these three entities I would like to perform following sql:

SELECT acc.name, acc.id
FROM account acc
JOIN book b on acc.book_id = b.id
JOIN organization org on b.organization_id = org.id
WHERE org.name = 'XYZ'

In this case Account entity has no relation with the Organization entity directly. Account entity has the relation via Book. How can I achieve this using hibernate criteria dynamic query?

Answer

LynAs picture LynAs · Jun 29, 2016

Another way

public List<Account> getAccountListByOrgName(String name){
    return sessionFactory.getCurrentSession().createCriteria(Account.class)
                .createAlias("book", "book")
                .createAlias("book.organization", "organization")
                .add(Restrictions.eq("organization.name", name))
                .list();
}