Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

java - How to add Distinct in Hibernate Criteria

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

where YourBean.class has a property "type". The returned list will be List<YourBean>.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...