G. Muqtada
G. Muqtada

Reputation: 162

column alias in hibernate projections

similar questions have been asked before, but not answered yet, i want to perform simple query as follow

select first_name as name from hr_employee

I need to alias column "first_name" as "name"

this is my controller

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

by running code we get "could not resolve property: name" as column defined in bean class is "first_name" not "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;
}
}
`

Upvotes: 0

Views: 2056

Answers (1)

Saqib Ahmed
Saqib Ahmed

Reputation: 1269

You have to make to setter and getter methods for name like:

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

there is no need to make variable "name"

your bean class shoul be like this:

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

then the Transformer will call the method setName();

Upvotes: 1

Related Questions