使用具有不同关系属性限制的 Hibernate Criteria

Using Hibernate Criteria with restrictions in different relationship attributes

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

涉及的实体简化如下:

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... */
}

在我的 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 :)