参考表上的Hibernate Criteria

时间:2015-07-01 05:13:47

标签: java hibernate spring-mvc

我有一个合并两个表的函数,每个表都有一个我要过滤的列。

@Entity
public class Contacts {
    @Id
    private int id;
    @ManyToOne //reference user_id = id
    private User user;
    @ManyToOne //reference people_id = id
    private People people;
    //getters and setters
}


@Entity
public class User {
   private int id;
   private int name;
   private Enterprise enterprise;
   //getters and setters
}



@Entity
public class People {
   private int id;
   private int name;
   //..others fields
   private Enterprise enterprise;
   //getters and setters
}

我需要列出我的企业ID = 1的所有“联系人”。在一个简单的选择(SQLServer)上,它将是:

 SELECT c.* FROM CONTACTS c
  INNER JOIN User u ON u.id = c.user_id
  INNER JOIN People p on p.id = p.people_id
  WHERE u.empresa_id = 1

我无法弄清楚如何使用Criteria API,我已经尝试了以下代码,但我一直收到错误。

//code..public List<Obj> list(int id) {
   Criteria crit = session.createCriteria(Contacts.class);
   crit.add(Restrictions.eq(user.enterprise.id, id)); //it doesn't work!
   crit.list();
}
  

org.hibernate.QueryException:无法解析属性:user.enterprise.id:sys.com.model.Contacts

1 个答案:

答案 0 :(得分:0)

这里我正在使用标准编写样本代码。

public List<Student_document> getUserById(int id) {
        Criteria criteria = sessionFactory.getCurrentSession().createCriteria(
                Student_document.class);
        criteria.add(Restrictions.eq("user_document.user_Id", id));
        return criteria.list();
    }