I have two entities:
public class Photo {
Long id;
String url;
@ManyToOne
@JoinColumn(name ="user_id")
User user;
// other fields and getters/setters
}
And second:
public class User {
Long id;
@OneToMany(mappedBy = "user")
private Collection<Photo> photos;
// other fields and getters/setters
}
I am trying to get this DTO:
public class UserDTO {
Long id;
List<String> photosUrls;
}
But I can't find the right solution. I wrote next criteria - find user with photos by login:
getCurrentSession().createCriteria(User.class, "user")
.createAlias("user.photos", "photos")
.setProjection(getUserProjection())
.add(Restrictions.eq("user.login",login))
.setResultTransformer(Transformers.aliasToBean(UserDTO.class))
.list();
// projection
getUserProjection() {
return Projections.projectionList()
.add(Projections.property("user.id"), "id")
.add(Projections.property("photos"), "url");
}
Also tried with HQL:
getCurrentSession()
.createQuery("select u.id, p.url " +
" from User u inner join u.photos p " +
" where u.login LIKE :login")
.setString("login", login)
.list();
But returned result is List<Object[]>
type but I need List<UserDTO>
.
Update:
HTTP Status 500 - Request processing failed; nested exception is org.springframework.orm.hibernate4.HibernateSystemException: IllegalArgumentException occurred while calling setter for property [com.memories.dto.UserDTO.photos(expected type = java.util.List)]; target = [com.memories.dto.UserDTO.photos@4e162869], property value = [https://i1.sndcdn.com/artworks-000031744302-0730nk-t500x500.jpg] setter of com.memories.dto.UserDTO.photos; nested exception is IllegalArgumentException occurred while calling setter for property [com.memories.dto.UserDTO.photos] (expected type = java.util.List)]; target = [com.memories.dto.UserDTO.photos@4e162869], property value = [https://i1.sndcdn.com/artworks-000031744302-0730nk-t500x500.jpg]
I think with the above code all you have to do it is to assign the resultant directly to List and it should work like a breeze. something like this.