0

我试图理解下面显示的代码

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 语句的吗?

4

2 回答 2

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名称值,对于连接中使用的列名,使用位于@JoinColumn注解中的值在 @OneToMany 或 @ManyToOne 注释附近

于 2015-09-14T08:32:57.383 回答
0

createAlias添加加入

就像是

...
FROM Payables p1
     JOIN Payment as p2 ON p2.paybles_id=p1.id
...

然后您可以使用连接表在 WHERE 部分添加条件

于 2015-09-14T08:27:38.993 回答