9

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?

Ivar
  • 6,138
  • 12
  • 49
  • 61
seal
  • 1,122
  • 5
  • 19
  • 37

2 Answers2

15

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();
}
LynAs
  • 6,407
  • 14
  • 48
  • 83
  • With same entities, what I supposed to do if I want to return list of Organization? – C.B. Feb 19 '19 at 11:09
14

you can do like this :

Criteria accountCriteria = getCurrentSession().createCriteria(Account.class,"acc");
Criteria bookCriteria =  accountCriteria .createCriteria("book","b");
Criteria orgCriteria =  bookCriteria.createCriteria("organization","org");
orgCriteria.add(Restrictions.eq("name", "XYZ"));

ProjectionList properties = Projections.projectionList();
properties.add(Projections.property("name"));
properties.add(Projections.property("id"));

accountCriteria.setProjection(properties);
accountCriteria.list();
Community
  • 1
  • 1
jpprade
  • 3,497
  • 3
  • 45
  • 58
  • where does the `criteria` comes from ? that is in line `criteria.createCriteria("book","b");` where the `criteria` object initialize ? – seal Jun 29 '16 at 13:52