NHibernate returning duplicate object in child collections when using Fetch

后端 未结 5 1879
轮回少年
轮回少年 2021-02-19 01:35

When doing a query like this (using Nhibernate 2.1.2):

 ICriteria criteria = session.CreateCriteria()
                .SetFetchMode(\"ChildColl         


        
相关标签:
5条回答
  • 2021-02-19 02:17

    You're doing a cartesian product here. Don't. Instead, fetch each collection separately.

    BTW: this isn't something NHibernate-specific, the same applies to any ORM in any platform, or even pure SQL without any ORM at all. In general, you don't want to fetch N*M rows when you can fetch N+M instead.

    0 讨论(0)
  • 2021-02-19 02:23

    I am not using NHibernate (rather, regular 'ol Hibernate), but in the Java version of Hibernate you can define One-To-Many collections as either Lists or Sets. If you define them as Sets you will not get duplicates. Surprisingly enough, this happens without overriding equals(). Unfortunately, I have the same problem and I want Lists so I can integrate with Wicket but no duplicates...

    0 讨论(0)
  • 2021-02-19 02:25

    Try using Futures:

    ICriteria criteriaFuture1
        = session.CreateCriteria<MyRootType>()
            .SetFetchMode("ChildCollection1", FetchMode.Eager)
            .Add(Restrictions.IdEq(id))
            .SetResultTransformer(Transformers.DistinctRootEntity)
            .FutureValue<MyRootType>();
     ICriteria criteriaFuture2
        = session.CreateCriteria<MyRootType>()
            .SetFetchMode("ChildCollection2", FetchMode.Eager)
            .Add(Restrictions.IdEq(id))
            .SetResultTransformer(Transformers.DistinctRootEntity)
            .FutureValue<MyRootType>();
    
     return criteriaFuture1.Value;
    
    0 讨论(0)
  • 2021-02-19 02:26

    What were you mapping your collection as? If your using a bag for example you will get duplicates. You can use a set instead and you won't get duplicates.

    0 讨论(0)
  • 2021-02-19 02:42

    You can select single distinct results by specifying SetResultsTransformer(Transformers.DistinctRootEntity);

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