Hibernate:使用Restrictions检索对象

时间:2013-11-06 07:19:43

标签: java hibernate

我最近开始在java中使用hibernate。

我有一个像这样的实体工作人员:

final public class Staff {
@Id @GeneratedValue
private int staffId;
private String firstName;
private String lastName;
private String Email;

@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "auth_id", nullable = false)
private Authentication auth;
//And all the getters and setters
}

我的身份验证类:

final public class Authentication {

@Id @GeneratedValue
@Column(name="auth_id")
private int authId;
private String pwd;
private String secretQuestion;
private String secretAnswer;
//And all the getters and setters
}

要登录,我需要查看电子邮件和密码。所以我创建了一个哈希地图:

Map<String, String> requirements = 
            new HashMap<String, String>();
            requirements.put("Email", "example@example.com");
                requirements.put("auth.pwd", "password");

然后运行查询:

Criteria criteria = session.createCriteria(currentClass);
            criteria.add(Restrictions.allEq(requirements));
staffList = (ArrayList<Staff>) criteria.list();

但是我得到了这个例外:

org.hibernate.QueryException: could not resolve property: auth.pwd of: models.Staff

我的问题是:我们如何为实体内的实体设置限制?

如果我遗漏了我应该提及的任何其他信息,请告诉我。谢谢!

1 个答案:

答案 0 :(得分:1)

auth实体的Staff属性使用别名:

Criteria crit = session.createCriteria(Staff.class, "staff");
crit.createAlias("auth", "a");  // Create alias for auth
crit.add(Restrictions.like("a.propertyName", propertyValue+"%"));