如何在Hibernate Criteria中添加Distinct [英] How to add Distinct in Hibernate Criteria
问题描述
在我的数据库中,我有一个测试表,列:testName,testType
有两个不同的测试,具有相同的类型即SUN,所以我只想要其中的一个我在其中使用Distinct hibernate / criteria如下,但它仍然给我两个与sun同名的类型。
In my database I have a Test table, with columns: testName, testType there are 2 different tests with the same type I.e "SUN", so I want only one of them for which I use Distinct in my hibernate / criteria as below, but it still giving me both the types with the same name as "sun".
Criteria crit = session.createCriteria(Test.class);
final ResultTransformer trans = new DistinctRootEntityResultTransformer();
crit.setResultTransformer(trans);
List rsList = trans.transformList(crit.list());
任何想法可能是什么原因,或任何其他方式过滤重复。
Any idea what could be the reason, or any other way of filtering duplicates.
推荐答案
使用Projections.distinct。
Use Projections.distinct.
Criteria crit = session.createCriteria(Test.class).setProjection(
Projections.distinct(Projections.projectionList()
.add(Projections.property("type"), "type") )
.setResultTransformer(Transformers.aliasToBean(YourBean.class));
List lst = crit.list();
其中YourBean.class有一个属性type。返回的列表将是 List< YourBean>
。
where YourBean.class has a property "type". The returned list will be List<YourBean>
.
这篇关于如何在Hibernate Criteria中添加Distinct的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!