hibernate投影中的列别名

时间:2017-03-27 12:56:53

标签: java hibernate

以前曾问过类似的问题,但尚未回答,我想按照以下方式执行简单的查询

select first_name as name from hr_employee

我需要将列“first_name”别名为“name”

这是我的控制器

`public @ResponseBody List EmployeeJson()
{
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
List list =  session.createCriteria(HrEmployee.class)       
.add(Restrictions.eq("employeeId", 1))      
.setProjection(Projections.projectionList()
.add(Projections.property("firstName"), "name") )
.setResultTransformer(Transformers.aliasToBean(HrEmployee.class)).list();
return list;
}`

通过运行代码,我们得到“无法解析属性:name”,因为bean类中定义的列是“first_name”而不是“name”。

`
@Table(name = "hr_employee")
@Entity
@JsonIgnoreProperties({"hibernateLazyInitializer"})
public class HrEmployee {

@Column(name="first_name")
private String firstName;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
`

1 个答案:

答案 0 :(得分:1)

您必须为名称设置setter和getter方法,如:

public void setName(String name){this.firstName = name;}
public String getName(){return this.firstName;}

无需变量“name”

你的豆类应该是这样的:

@Table(name = "hr_employee")
@Entity
@JsonIgnoreProperties({"hibernateLazyInitializer"})
public class HrEmployee {

    @Column(name="first_name")
    private String firstName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public void setName(String name){
        this.firstName = name;
    }
    public String getName(){
        return this.firstName;
    }
}

然后Transformer将调用方法setName();