[英]How to return specific type instead of List<Object[]> in Hibernate Criteria?
I have two classes 我有两节课
@Entity
public class user implements Serializable{
...
private Set<article> uploaded = new HashSet<article>();
...
@OneToMany(mappedBy="uploader")
public Set<article> getUploaded() {
return uploaded;
}
@Entity
public class article implements Serializable{
....
private user uploader;
....
@ManyToOne
public user getUploader() {
return uploader;
}
So there also are two tables in the database: user and article. 因此,数据库中还有两个表:user和article。 I try to get data using Criteria:
我尝试使用条件获取数据:
tx = session.beginTransaction();
Criteria cr = session.createCriteria(article.class);
...
List<article> list = cr.list();
But the returned list is not List<article>
, it's a List<Object>
contains ARTICLE and USER, and I don't know how to get the ARTICLE data from the list. 但是返回的列表不是
List<article>
,而是一个包含ARTICLE和USER的List<Object>
,我不知道如何从列表中获取ARTICLE数据。 if I set FetchType.Lazy, then the returned list will be List<article>
without USER data, but I also need the USER data... 如果我设置FetchType.Lazy,那么返回的列表将是没有用户数据的
List<article>
,但是我也需要用户数据...
The Criteria Hibernate class list()
method return a raw List. Criteria Hibernate类的
list()
方法返回一个原始List。 So if you try to cast it you get an unchecked warning. 因此,如果您尝试投射它,则会收到未经检查的警告。
But the returned list is not List, it's a List contains ARTICLE and USER
但是返回的列表不是List,它是一个包含ARTICLE和USER的列表
It doesn't contain both article and user, it contains only the type you passed when you create the criteria. 它既不包含文章也不包含用户,它仅包含您在创建条件时传递的类型。 In this case:
在这种情况下:
Criteria cr = session.createCriteria(article.class);
The list returned will contain article objects. 返回的列表将包含文章对象。
You can get a list of article in different ways: 您可以通过不同的方式获取文章列表:
The easiest one: 最简单的一个:
//Cast the raw list, but this will give you an unchecked warning
List<article> list = (List<article>) cr.list();
Or you can copy the values in another list: 或者,您可以将值复制到另一个列表中:
List<Object> list = cr.list();
List<article> articles = new ArrayList<article>();
for(Object object : list) {
if(object instanceof article) {
articles.add((article) object);
}
}
Look at this post : What is the "proper" way to cast Hibernate Query.list() to List<Type>? 看一下这篇文章: 将Hibernate Query.list()强制转换为List <Type>的“正确”方法是什么?
Anyway, class names must start with an uppercase character for java naming conventions. 无论如何,对于Java命名约定,类名称必须以大写字母开头。 article -> Article, user -> User
文章->文章,用户->用户
Use Projection or ResultSetTransformer: 使用Projection或ResultSetTransformer:
.setResultTransformer(Transformers.aliasToBean(article.class)); .setResultTransformer(Transformers.aliasToBean(article.class));
it's easy to google. 谷歌很容易。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.