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

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;
}`


通过运行代码,我们得到“无法解析属性:名称”,因为在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;
}
}
`

最佳答案

您必须为名称使用setter和getter方法,例如:

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


无需设置变量“名称”

您的bean类应该是这样的:

@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()方法;

关于java - hibernate 投影中的列别名,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43047130/

10-13 04:56