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?
Fixed it.
Had to change my projection so it looked like this..
.add(Projections.property("userName"), "userName")
Odd.. but whatever works I guess.
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With