我想了解下面显示的代码
Criteria criteria = session.createCriteria(Payables.class);
criteria.add(Restrictions.eq("companyId", companyId));
criteria.createAlias("makePayment", "makePayment");
if (creditorId != null) {
criteria.createAlias("makePayment.creditor", "creditor");
criteria.add(Restrictions.eq("creditor.id", creditorId));
}
criteria.add(Restrictions.eq("journalEntryId", journalEntryId));
我确实知道createCriteria会做什么,但添加createAlias会让我感到困惑。我已经阅读了文档,但一切仍然模糊不清。
你能告诉我上面的代码如何使用mysql语句?
答案 0 :(得分:1)
Criteria criteria = session.createCriteria(Payables.class);
// select * from Payables p;
criteria.add(Restrictions.eq("companyId", companyId));
// where p.companyId = :companyId
criteria.createAlias("makePayment", "makePayment");
// inner join Payement makePayment on makePayement.payables_id = p.id
if (creditorId != null) {
criteria.createAlias("makePayment.creditor", "creditor");
// inner join Creditor c on c.payement_id = makePayement.id
criteria.add(Restrictions.eq("creditor.id", creditorId));
// where c.id = :creditorId
}
criteria.add(Restrictions.eq("journalEntryId", journalEntryId));
// where p.journalEntryId = :journalEntryId
结果是:
select * from Payables p
inner join Payement makePayment on makePayement.payables_id = p.id
inner join Creditor c on c.payement_id = makePayement.id
where p.companyId = :companyId
and c.id = :creditorId
and p.journal_entry_id = :journalEntryId
对于表名,使用实体的@Table注释中的值,对于列名,使用位于字段或getter上的@Column名称值,对于join中使用的列名,使用@中的值位于@OneToMany或@ManyToOne注释附近的JoinColumn注释
答案 1 :(得分:0)
createAlias
添加了加入
类似
...
FROM Payables p1
JOIN Payment as p2 ON p2.paybles_id=p1.id
...
然后,您可以使用联接表在WHERE部分
中添加条件