Hibernate标准如何不加载孩子们

时间:2015-07-30 07:21:05

标签: java hibernate hibernate-mapping hibernate-criteria

您好我有三个实体用户,候选人(求职者)和面试。我想加载对候选人的访谈,但是对于候选人,它会加载用户。我试图通过注释解决把懒惰放到求职者 - 用户关系它可以工作,但是当我想用用户加载求职者时不给代理会话。我想我必须从标准中解决问题。

我的采访实体:

    @Entity
    @Table(name = "INTERVIEW")
    public class Interview extends BaseEntity {

    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name = "job_id", nullable=false)
    @Expose
    @NotNull
    private Job job;

    /** candidates for interview */
    @ManyToOne
    @JoinColumn(name = "job_seeker_id", nullable=false)
    @Expose
    @NotNull
    private JobSeeker candidate;
    .
    .
    .

求职者实体:

    @Entity
    @Table(name="JOB_SEEKER") 
    public class JobSeeker extends BaseEntity{

    @OneToOne
    @JoinColumn(name = "user_id")
    private User user;
    .
    .
    .

用户实体:

    @Entity
    @Table(name="USER_AUTH")
    public class User extends BaseEntity {

    @OneToOne(mappedBy = "user", cascade=CascadeType.ALL)
    private JobSeeker jobSeeker;
    .
    .
    .

标准:

Session session = getCurrentSession();
Criteria criteria = session
    .createCriteria(Interview.class, "interview")
    .setFirstResult(dataTableFilter.iDisplayStart)
    .setMaxResults(dataTableFilter.iDisplayLength)
    .createAlias("interview.candidate", "candidate");

现在它正在工作,但是因为用户,n面试使n查询,当我把懒惰放在jobseeker用户写1查询但我不能放懒。我在stackoverlow上搜索,我看到像

这样的延迟加载
.setFetchMode("candidate.user", FetchMode.SELECT) 

.setFetchMode("candidate.user", FetchMode.LAZY)

但它对我没有用,它也写了n查询。我可以以某种方式判断标准是不用jobSeeker加载用户子项,还是延迟加载用户的其他选项?

解: 通过投影,我现在解决了我的标准如下:

Criteria criteria = session
        .createCriteria(Interview.class, "interview")
        .setFirstResult(dataTableFilter.iDisplayStart)
        .setMaxResults(dataTableFilter.iDisplayLength)
        .createAlias("interview.job", "job")
        .createAlias("interview.candidate", "candidate"))
        .setProjection(Projections.projectionList()
                .add(Projections.property("id"), "id")
                .add(Projections.property("status"), "status")
                .add(Projections.property("date"), "date")
                .add(Projections.property("candidate.name"), "candidate.name"))
                    .setResultTransformer(new AliasToBeanNestedResultTransformer(Interview.class));

现在只选择面试ID,状态,日期和候选人姓名。简单的AliasToBeanTransformer对candidate.name不起作用,我找到了一个很好的变换器巫婆。链接:https://github.com/samiandoni/AliasToBeanNestedResultTransformer

1 个答案:

答案 0 :(得分:2)

Session session = getCurrentSession();

Criteria criteria = session
.createCriteria(Interview.class, "interview")
.setFirstResult(dataTableFilter.iDisplayStart)
.setMaxResults(dataTableFilter.iDisplayLength)
.createAlias("interview.candidate", "candidate")
.createAlias("candidate.user",  JoinType.NONE);

您还可以设置此条件之外的投影