分配对象的休眠标准

时间:2011-10-10 16:15:05

标签: java hibernate criteria hibernate-criteria

我有DTO对象的下一个结构:

public class MainDTO implements Serializable {
    private Long mainId;
    private String name;
    ... //some other fields
    private boolean disabled;

    @ManyToOne()
    @JoinColumn(name = "root_id")
    private RootDTO root;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "child_id", updatable = false, referencedColumnName = "child_id")
    @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
    private ChildDTO child;

    ...
}

public class RootDTO implements Serializable {
    ... //some other fields
    private boolean disabled;

    ...
}


public class ChildDTO implements Serializable {
    private Long childId;
    ... //some other fields
    private boolean disabled;

    @ManyToOne()
    @JoinColumn(name = "info_id")
    private InfoDTO info;

    ...
}

public class InfoDTO implements Serializable {
    private Long infoId;
    ... //some other fields
    private boolean disabled;

    ...
}

我需要填写Map<String, Map<Long, Long>><name from MainDTO, <mainId from MainDTO, infoId from InfoDTO >>)下一个限制:

MainDTO.disabled = false,

MainDTO.root!= null,

MainDTO.root.disabled = false,

MainDTO.child.disabled = false,

MainDTO.child.info!= null,

MainDTO.child.info.disabled = false

以下是我编写的代码,但卡在了InfoDTO的选择信息中:

Criteria rootCriteria = getSession().createCriteria(
        MainDTO.class);

// check that root is enabled
rootCriteria.createCriteria("root", "root").add(
    Restrictions.eq("disabled", false));

// check that child is enabled
Criteria childCriteria = rootCriteria
    .createCriteria("child", "child")
    .add(Restrictions.eq("disabled", false))
    .add(Restrictions.isNotNull("info"));

// check that info is enabled
childCriteria
    .createCriteria("info", "info")
    .add(Restrictions.eq("disabled", false));

ProjectionList rootProjection = Projections.projectionList()
    .add(Projections.property("mainId"))
    .add(Projections.property("name"))
    .add(Projections.property("child.info")); //HOW TO SELECT ONLY ID??
rootCriteria.setProjection(rootProjection);
rootCriteria.add(Restrictions.eq("disabled", false))
    .add(Restrictions.isNotNull("root"))
    .add(Restrictions.isNotNull("child"));

非常感谢!

1 个答案:

答案 0 :(得分:0)

首先,调用实体DTO真的很混乱。

现在关于您的问题,您应该使用在投影中定义的别名

ProjectionList rootProjection = 
    Projections.projectionList()
               .add(Projections.property("mainId"))
               .add(Projections.property("name"))
               .add(Projections.property("info.infoId"));

另外,假设您正在对root和child进行内部联接,则最后两个限制不是必需的:内部联接已经确保它们不为空。