使用休眠条件和不同关系属性中的限制



所以我正在开发一个基于 JSF 2.3 Hibernate 4.3 的类似法院的应用程序,我正在努力弄清楚如何使用 Hibernate Criteria API 构建给定的查询。这个想法是选择经过身份验证的用户涉及的所有进程。

涉及的实体简化如下:

用户.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 中,我想列出用户在某种程度上参与的过程(作为法官或作为当事人或作为当事人的律师(。所以这是我使用 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();
}
}

挑战在于将限制添加到关系(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:)

最新更新