[英]Using Hibernate Criteria with restrictions in different relationship attributes
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. 這個想法是 select 認證用戶參與的所有進程。
所涉及的實體簡化如下:
用戶.java
@Entity
@Table(name = "tb_users")
public class User implements Serializable {
@Id
@GeneratedValue
private Long id;
@ManyToOne
private User lawyer;
/* other attributes, getters, setters... */
}
制程.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... */
}
在我的 bean 中,我想列出用戶在某種程度上參與的流程(作為法官或作為當事人或作為當事人的律師)。 所以這是我使用 Criteria 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();
}
}
挑戰是在關系(4和5)的關系中添加限制,而其他的單獨工作正常。
有人可以幫我弄清楚如何構建這個查詢嗎?
我做了這樣的事情,它似乎工作 - 生成的查詢看起來不是超級干凈(我不希望它):
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")
));
別名是這里的關鍵,不用擔心123
:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.