Hibernate使用投影部分填充对象

时间:2012-07-24 16:16:44

标签: java hibernate

我的问题与此SO question完全相同。

假设我们有像

这样的实体
public class Employee {
    Long getId();
    String getName();
    Address getAddress();  
}

在createCriteria和Projections的帮助下,我们尝试从地址表中获取id,来自用户和城市的名称。

我们遇到的问题是,城市没有设置为对象城市财产。

以下是我们尝试的代码:

 Criteria cr = session.createCriteria(Employee.class)
                    .setProjection(Projections.projectionList()
                    .add(Projections.property("id"), "id")
                    .add(Projections.property("Name"), "Name")
                    .add(Projections.property("address.city"), "address.city"))
                    .addOrder(Order.asc("address.city"))
                    .createAlias("address", "address")
                    .setResultTransformer(Transformers.aliasToBean(Employee.class));

基于JBNizet对上述问题的评论我理解部分对象是坏主意,但如果我被授权这样做,我该如何实现呢?任何意见都将不胜感激。

2 个答案:

答案 0 :(得分:3)

使用AliasToBeanConstructorResultTransformer,并在您的实体中定义如下构造函数:

public Employee(Long id, String name, String city) {
    this.id = id;
    this.name = name;
    this.address = new Address();
    this.address.setCity(city);
}

或者,(这是我首选的解决方案,因为它避免了反射并允许以较低的风险重构代码)不要使用任何结果转换器并自己构建实例:

List<Object[]> rows = criteria.list();
List<Employee> result = new ArrayList<Employee>(rows.size());
for (Object[] row : rows) {
    Employee e = new Employee();
    e.setId((Long) row[0]);
    e.setName((String) row[1]);
    Address address = new Address();
    address.setCity((String) row[2]);
    e.setAddress(address);
    result.add(e);
}    

答案 1 :(得分:0)

你也可以试试这个:

Criteria cr = session.createCriteria(Employee.class)
                    .setProjection(Projections.projectionList()
                    .add(Projections.property("id"), "id")
                    .add(Projections.property("name"), "name")
                    .add(Projections.property("address.city"), "addressCity"))
                    .addOrder(Order.asc("address.city"))
                    .createAlias("address", "address")
                    .setResultTransformer(Transformers.aliasToBean(Employee.class));

还要在Employee类中为addressCity添加setter

public void setAddressCity( String addressCity ){
    address.setCity(addressCity);
}

无需提及Employee的构造函数,也应该实例化Address对象。