Hibernate Criteria API多个连接

时间:2010-08-02 16:14:33

标签: java hibernate orm criteria hibernate-criteria

我的hibernate实体如下:

@Entity
@Table(name = "EditLocks")
public class EditLock extends AuditableEntity {

    /** The document that is checked out. */
    @OneToOne
    @JoinColumn(name = "documentId", nullable = false)
    private Document document;

文件看起来像这样:

public class Document extends AuditableEntity {
    /** Type of the document. */
    @ManyToOne
    @JoinColumn(name = "documentTypeId", nullable = false)
    private DocumentType documentType;

基本上我想写的查询是:

Select * from EditLocks el, Document docs, DocumentTypes dt where el.documentId = docs.id and docs.documentTypeId = dt.id and dt.id = 'xysz';

如何使用hibernate条件api执行此操作?

2 个答案:

答案 0 :(得分:8)

应该这样做:

Criteria criteria = getSession().createCriteria(EditLock.class);
criteria.createAlias( "document", "document" );
criteria.createAlias( "document.documentType", "documentType" );
criteria.add(Restrictions.eq("documenttype.id", "xyz");

您需要添加别名才能到达具有您要查询的属性的对象。

答案 1 :(得分:0)

所以看起来你只是试图获得具有DocumentType id ='xyz'的Documents的EditLocks。我假设Document和DocumentType具有标准的Hibernate映射:

Criteria crit = getSession().createCriteria(EditLock.class);
crit.add(Restrictions.eq("document.documenttype.id", "xyz");

Hibernate应该能够找到你想要的联接。

相关问题