gpt4 book ai didi

java - Hibernate hql/criteria 结果包含集合

转载 作者:太空宇宙 更新时间:2023-11-04 13:46:04 25 4
gpt4 key购买 nike

我有两个实体:

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 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]

最佳答案

我认为使用上面的代码,您所要做的就是将结果直接分配给 List,它应该轻而易举地工作。像这样的东西。

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

关于java - Hibernate hql/criteria 结果包含集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30831470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com