复杂的Hibernate预测

Fau*_*mad 5 java hibernate criteria

我想问一下,有可能我创建了多个级别的查询预测和标准吗?我有2个模型类:

@Entity  
@Table(name = "person")  
public class Person implements Serializable {
    @Id
    @GeneratedValue
    private int personID;
    private double valueDouble;
    private int valueInt;
    private String name;
    @OneToOne(cascade = {CascadeType.ALL}, orphanRemoval = true)
    @JoinColumn(name="wifeId")
    private Wife wife;
       /*   
        *  Setter Getter    
        */
}


@Entity 
@Table(name = "wife")  
public class Wife implements Serializable {

    @Id
    @GeneratedValue     
    @Column(name="wifeId")
    private int id;
    @Column(name="name")
    private String name;
    @Column(name="age")
    private int age;            
    /*
     *  Setter Getter
     */       
}
Run Code Online (Sandbox Code Playgroud)

我的标准API:

ProjectionList projections = Projections.projectionList(); 
projections.add(Projections.property("this.personID"), "personID");
projections.add(Projections.property("this.wife"), "wife");
projections.add(Projections.property("this.wife.name"), "wife.name");

Criteria criteria = null; 
criteria = getHandlerSession().createCriteria(Person.class); 
criteria.createCriteria("wife", "wife", JoinType.LEFT.ordinal()); 
criterion = Restrictions.eq("wife.age", 19);  
criteria.add(criterion); 
criteria.setProjection(projections);
criteria.setResultTransformer(Transformers.aliasToBean(Person.class)); 
return criteria.list();
Run Code Online (Sandbox Code Playgroud)

我希望,我可以使用指定的妻子属性标准查询Person,并指定返回resultSet.所以我使用Projections获取指定的返回resultSet

我想要personID,姓名(人),姓名(妻子)将返回.API我必须如何使用,我更喜欢使用Hibernate Criteria API.

这一次,我使用上面的代码来获得我的预期结果,但它会抛出异常,并显示错误消息: Exception in thread "main" org.hibernate.QueryException: could not resolve property: wife.name of: maladzan.model.Person以及我Restrictions.eq("wife.age", 19);是否正确获得有妻子19岁的人作为她的年龄值?

谢谢

Fir*_*iro 6

AFAIK使用aliastobean变压器不可能投射多个深度.你的选择是

  • 创建展平的数据传输对象(DTO)
  • 自己在内存中填充结果人
  • 实现自己的resulttransformer(类似于选项2)

选项1看起来像这样:

Criteria criteria = getHandlerSession().createCriteria(Person.class)
    .createAlias("wife", "wife", JoinType.LEFT.ordinal())
    .add(Restrictions.eq("wife.age", 19)); 
    .setProjection(Projections.projectionList()
        .add(Projections.property("personID"), "personID")
        .add(Projections.property("name"), "personName")
        .add(Projections.property("wife.name"), "wifeName"));
    .setResultTransformer(Transformers.aliasToBean(PersonWifeDto.class));

return criteria.list();
Run Code Online (Sandbox Code Playgroud)


小智 5

我写了ResultTransformer,这完全是这样做的.它的名字是AliasToBeanNestedResultTransformer,在github上查看.