Hibernate hql / criteria结果包含集合 [英] Hibernate hql/criteria result contains collection

查看:180
本文介绍了Hibernate hql / criteria结果包含集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个实体:

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
}

我试图得到这个DTO:

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

还尝试了HQL:

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();

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

But returned result is List<Object[]> type but I need List<UserDTO>.

更新:


HTTP状态500 - 请求处理失败;嵌套异常是
org.springframework.orm.hibernate4.HibernateSystemException异常:
调用setter属性
时发生IllegalArgumentException [com.memories.dto.UserDTO.photos(expected type = java.util。清单);
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;嵌套的异常是
在为属性
[com.memories.dto.UserDTO.photos](expected type = java.util.List)]调用setter时发生IllegalArgumentException;
target = [com.memories.dto.UserDTO.photos@4e162869],property value =
[ https://i1.sndcdn.com/artworks-000031744302-0730nk-t500x500.jpg]


推荐答案

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

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.

List<User> userList = yourCriteria.list();

这篇关于Hibernate hql / criteria结果包含集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆