Reputation: 307
So I'm working on a Court like application based on JSF 2.3 Hibernate 4.3 and I'm struggling to figure out how to build a given query using Hibernate Criteria API. The idea is to select all processes the authenticated user is involved with.
The entities involved are simplified below:
User.java
@Entity
@Table(name = "tb_users")
public class User implements Serializable {
@Id
@GeneratedValue
private Long id;
@ManyToOne
private User lawyer;
/* other attributes, getters, setters... */
}
Process.java
@Entity
@Table(name = "tb_processes")
public class Process implements Serializable {
@Id
@GeneratedValue
private Long id;
@ManyToOne
private User judge;
@ManyToOne
private User promoterParty;
@ManyToOne
private User promotedParty;
/* other attributes, getters, setters... */
}
In my bean, I want to list the processes which the user is involved in some level (as judge OR as party OR as party's lawyer). So this is the closest I could get using Criateria API:
@Named
@RequestScoped
public class IndexBean implements Serializable {
@Inject
private ExternalContext externalContext;
public List<Process> getProcesses() {
HttpSession httpSession = (HttpSession) externalContext.getSession(false);
User user = (User) httpSession.getAttribute("auth");
Criteria criteria = dao.criteria(Process.class);
criteria.add(Restrictions.or(
/* 1 */ Restrictions.eq("judge.id", user.getId()), // works fine
/* 2 */ Restrictions.eq("promoterParty.id", user.getId()), // works fine
/* 3 */ Restrictions.eq("promotedParty.id", user.getId()), // works fine
/* 4 */ Restrictions.eq("promoterParty.lawyer.id", user.getId()), // [fail] org.hibernate.QueryException: could not resolve property: promoterParty.lawyer.id of: com.example.model.Process
/* 5 */ Restrictions.eq("promotedParty.lawyer.id", user.getId()) // [fail] org.hibernate.QueryException: could not resolve property: promotedParty.lawyer.id of: com.example.model.Process
));
return criteria.list();
}
}
The challange is to add the restriction to the relationship of the relationship (4 and 5), while the other ones alone work fine.
Can someone help me figure out how I can build this query?
Upvotes: 0
Views: 1089
Reputation: 5592
I did something like this and it seems to work - generated query does not look super clean (and I wouldn't expect it to):
Criteria criteria = sess.createCriteria(Process.class);
criteria
.createAlias("promoterParty.lawyer", "promoterLawyer")
.createAlias("promotedParty.lawyer", "promotedLawyer")
.add(Restrictions.or(
Restrictions.eq("judge.id", "123"),
Restrictions.eq("promoterLawyer.id", "123"),
Restrictions.eq("promotedLawyer.id", "123")
));
Aliases are the key thing here, don't worry about 123
:)
Upvotes: 1