Hibernate - 在Criteria Restrictions中添加另一个类的属性

时间:2017-09-21 12:19:27

标签: java database hibernate hibernate-criteria

我有一个表贷款申请,其pojo是

class LoanApplication{
int id;
int loanNo;
...
}

我有另一个pojo

class LoanFlow{
int id;
int loanId;
date reviewDate;
...
}

这里loanFlow的loanId是映射到LoanApplication的id的外键。

我必须使用reviewDate获取所有贷款申请。

我正在尝试编写一个标准:

Criteria criteria = getSession().createCriteria(LoanApplication.class);
criteria.add(Restrictions.eq("id", someId));

如何使用此条件从LoanFlow中获取reviewDate。

2 个答案:

答案 0 :(得分:1)

Criteria criteria = getSession().createCriteria(LoanApplication.class, "loApp");
criteria.createAlias("loApp.loanFlow", "flow");
criteria.add(Restrictions.eq("flow.id", 1));
  

您也可以直接使用HQL。   使用createQuery()

答案 1 :(得分:0)

如果实体之间的关系没有ManyToOne或OneToMany注释,则可以使用子查询执行此操作:

DetachedCriteria subQuery = DetachedCriteria.forClass(LoanFlow.class, "loanFlow");

/*Here there is a between, but you can change it to your necessity*/
subQuery.add(Restrictions.between("loanFlow.reviewDate", dateBegin, dateEnd));
subQuery.setProjection(Projections.property("loanFlow.loanId"));

Criteria criteria = getSession().createCriteria(LoanApplication.class, "loanApplication");        
Subqueries.propertyIn("loanApplication.id", subQuery);

List<LoanApplication> list = criteria.list();