Hibernate hql / criteria结果包含集合

时间:2015-06-13 17:31:08

标签: java hibernate hql hibernate-criteria

我有两个实体:

public class Photo {
   Long id;
   String url;
   @ManyToOne
   @JoinColumn(name ="user_id")
   User user;
   // other fields and getters/setters
}

第二名:

public class User {
   Long id;
   @OneToMany(mappedBy = "user")
   private Collection<Photo> photos;
   // other fields and getters/setters
}

我想要获得这个DTO:

public class UserDTO {
    Long id;
    List<String> photosUrls;
}

但我无法找到合适的解决方案。我写了下一个标准 - 通过登录找到带照片的用户:

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");
    }

还尝试使用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();

但是返回的结果是List<Object[]>类型,但我需要List<UserDTO>

更新

  

HTTP状态500 - 请求处理失败;嵌套异常是   org.springframework.orm.hibernate4.HibernateSystemException:   调用属性的setter时发生IllegalArgumentException   [com.memories.dto.UserDTO.photos(expected type = java.util.List)];   target = [com.memories.dto.UserDTO.photos@4e162869],属性值=   [https://i1.sndcdn.com/artworks-000031744302-0730nk-t500x500.jpg]   com.memories.dto.UserDTO.photos的setter;嵌套异常是   调用属性的setter时发生IllegalArgumentException   [com.memories.dto.UserDTO.photos](期望的类型= java.util.List)];   target = [com.memories.dto.UserDTO.photos@4e162869],属性值=   [https://i1.sndcdn.com/artworks-000031744302-0730nk-t500x500.jpg]

2 个答案:

答案 0 :(得分:1)

我认为使用上面的代码,你所要做的就是将结果直接分配给List,它应该像微风一样工作。像这样的东西。

{{each-in}}

答案 1 :(得分:0)

所以,我发现不是最好的解决方案,但是......

首先,需要获取实体列表User:

List<User> list = getCurrentSession()
                .createQuery("from USer as u where u.login LIKE :login")
                .setString("login", login)
                .list();

接下来,我们在实体用户方法中声明,将List<Photo>转换为List<String>

public List<String> getPhotosUrls() {
    List<String> urls = new ArrayList<String>(photos.size());
    for (Photo p : photos)
        urls.add(p.getUrl()));
    return urls;
}

最后一步是硬编码创建DTO bean:

List<UserDTO> users = new ArrayList<UserDTO>(list.size());
for (User u : list) {
    users.add(new UserDTO(u.id, u.getPhotosUrls));

当然,您必须拥有UserDTO(Long id, List<String> urls)构造函数。 如果有人会找到更好的解决方案,请写在这里:)