Is it valid for Hibernate list() to return duplicates?

后端 未结 4 699
-上瘾入骨i
-上瘾入骨i 2020-12-09 08:35

Is anyone aware of the validity of Hibernate\'s Criteria.list() and Query.list() methods returning multiple occurrences of the same entity?

相关标签:
4条回答
  • 2020-12-09 08:43

    I had the exact same issue with Criteria API. The simple solution for me was to set distinct to true on the query like

    CriteriaQuery<Foo> query = criteriaBuilder.createQuery(Foo.class);
    query.distinct(true);
    

    Another possible option that came to my mind before would be to simply pass the resulting list to a Set which will also by definition have just an object's single instance.

    0 讨论(0)
  • 2020-12-09 08:46

    I also started noticing this behavior in my Java API as it started to grow. Glad there is an easy way to prevent it. Out of practice I've started out appending:

    .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
    

    To all of my criteria that return a list. For example:

    List<PaymentTypeAccountEntity> paymentTypeAccounts = criteria()
      .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY)
      .list();
    
    0 讨论(0)
  • 2020-12-09 08:48

    Yes, getting duplicates is perfectly possible if you construct your queries so that this can happen. See for example Hibernate CollectionOfElements EAGER fetch duplicates elements

    0 讨论(0)
  • 2020-12-09 08:51

    If you have an object which has a list of sub objects on it, and your criteria joins the two tables together, you could potentially get duplicates of the main object.

    One way to ensure that you don't get duplicates is to use a DistinctRootEntityResultTransformer. The main drawback to this is if you are using result set buffering/row counting. The two don't work together.

    0 讨论(0)
提交回复
热议问题