Hibernate条件使用GROUP BY和RETURN ENTITY LIST [英] Hibernate criteria Using GROUP BY and RETURN ENTITY LIST
问题描述
我试着在我的标准中使用 GROUP BY
。我需要这样做:
SELECT b FROM Book b GROUP BY volumeCode;
我有以下代码:
Criteria c = s.createCriteria(Book.class);
c.setProjection(Projections.projectionList()。add(Projections.groupProperty(volumeCode)));
列表< Book> result = c.list();
但是这个标准只返回 volumeCode
s(字符串列表)。我需要获取 Book
s的列表。所以我试图使用变形金刚:
Criteria c = s.createCriteria(Book.class);
c.setProjection(Projections.projectionList()。add(Projections.groupProperty(volumeCode)));
c.setResultTransformer(Transformers.aliasToBean(Book.class));
列表< Book> result = c.list();
该代码返回空值列表。是否有可能通过标准来做到这一点?
首先,projecton过滤检索的数据量,如果你想更多数据,您应该将这些属性也添加到投影中。
示例:
c.setProjection(Projections.projectionList()
.add(Projections.property(id)。as(id))
.add(Projections.property(descripction ).as(description))
.add(Projections.groupProperty(volumeCode)。as(volumeCode)));
现在,变压器完成它所说的Bean的别名,它与
编辑:
如果没有变换器,如果投影有多个属性,结果如下所示:
for(Object [] item:criteria.list()) {
System.out.println((String)item [0]); // ID
System.out.println((String)item [1]); //描述
System.out.println((String)item [2]); //体积代码
}
这就是为什么你会得到演员例外,关于变压器,尝试将每个别名与您的java bean的属性名称进行匹配。
I'm trying to use GROUP BY
in my criteria. I need to do this:
SELECT b FROM Book b GROUP BY volumeCode;
I have following code:
Criteria c = s.createCriteria(Book.class);
c.setProjection(Projections.projectionList().add(Projections.groupProperty("volumeCode")));
List<Book> result = c.list();
But this criteria returns only volumeCode
s (a list of Strings). I need to get a list of Book
s. So I tried to use Transformers:
Criteria c = s.createCriteria(Book.class);
c.setProjection(Projections.projectionList().add(Projections.groupProperty("volumeCode")));
c.setResultTransformer(Transformers.aliasToBean(Book.class));
List<Book> result = c.list();
This code returns list of null values. Is it possible to do that with criteria?
First of all, the projecton filters the amount of data retrieved, if you want more data, you should add those properties to the projection too.
Example:
c.setProjection( Projections.projectionList()
.add( Projections.property("id").as("id") )
.add( Projections.property("descripction").as("description") )
.add( Projections.groupProperty("volumeCode").as("volumeCode") ));
Now, the transformer does what it says "Alias to Bean", it does an alias match with the properties of your java bean "Book.java".
Edit:
Without the transformer, if the projection has more than one property, the result comes out like this:
for(Object[] item:criteria.list()){
System.out.println( (String)item[0] ); //ID
System.out.println( (String)item[1] ); //Description
System.out.println( (String)item[2] ); //Volume code
}
Thats why you were getting the cast exception, about the transformer, try to match every alias with the property name of your java bean.
这篇关于Hibernate条件使用GROUP BY和RETURN ENTITY LIST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!