Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Hibernate aliasToBean() not working

Tags:

hibernate

The following code isn't working for me:

List results = getSession().createCriteria(User.class)
    .setProjection(Projections.projectionList()
            .add(Projections.property("userName"))
    )
    .setResultTransformer(Transformers.aliasToBean(UserSummary.class))
    .list();


Funny enough though if I remove the setResultTransformer() I get a list of userNames returned back perfectly fine.

Here is my UserSummary class:

public class UserSummary {

    private String userName;
    private String clickUrl;
    private Integer id;

    public UserSummary() {}

    public UserSummary(Integer id, String userName) {
        this.id = id;
        this.userName = userName;
        this.clickUrl = clickUrl;
    }

    public String getUserName() {
        return userName;
    }

    public String getClickUrl() {
        return clickUrl;
    }

    public void setClickUrl(String clickUrl) {
        this.clickUrl = clickUrl;
    }

    public Integer getId() {
        return id;
    }
}


Thoughts?

like image 954
Shane Courtrille Avatar asked Dec 21 '10 21:12

Shane Courtrille


2 Answers

Fixed it.

Had to change my projection so it looked like this..

.add(Projections.property("userName"), "userName")

Odd.. but whatever works I guess.

like image 105
Shane Courtrille Avatar answered Nov 09 '22 04:11

Shane Courtrille


.add(Projections.property("userName"), "userName");

..is correct in this situation.

The aliasToBean() method creates a ResultTransformer that will inject aliased values into instances of the UserSummary class via property methods or fields. The second parameter of the add() method is where the projected property alias is specified. Here you have specified 'userName' which is the property in the UserSummary class the projected property will be mapped to. That's why it didn't work in the first instance. The Hibernate lib did not know what UserSummary field/setter to map the property to. Take out the aliasToBean() method and it isn't going to attempt to do any mapping. So, if one had:

private String userFullName;

public UserSummary(Integer id, String userFullName) {
   this.id = id;
   this.userFullName = userFullName;
   this.clickUrl = clickUrl;
}

public String getUserFullName() {
   return userFullName;
}

The add() method would be as follows:

.add(Projections.property("userName"), "userFullName");

As long as both userName of the User class and userFullName of UserSummary class are using the same type you're good to go.

like image 20
mcksn Avatar answered Nov 09 '22 05:11

mcksn