0

I am trying to load single Merchant entity with its Categories, and relationship between Merchant and Category is Many-To-Many. Also Category entity has also translations... So I wrote following code to retrieve data that I need from database:

Merchant merchant = queryFactory.selectFrom(QMerchant.merchant)
        .leftJoin(QMerchant.merchant.categories, QMerchantCategory.merchantCategory).fetchJoin()
        .leftJoin(QMerchantCategory.merchantCategory.translations, QMerchantCategoryTranslation.merchantCategoryTranslation).fetchJoin()
        .where(QMerchant.merchant.id.eq(merchantStore.getMerchant().getId()))
        .fetchOne();

However, what I get as a result is Merchant that has list of three categories (that are same) and each with three translation objects...

enter image description here

I can check in database that there is only one category in replationship with merchant that I am trying to load, and as you can see from the picture from JVM IDs that those are all same instances... Also following code gives same result:

@EntityGraph(attributePaths = {"categories", "categories.translations"})
Optional<Merchant> findWithCategoriesById(long id);

If add another translation then I will have merchant with four categories...

So how do I tell hibernate to load Merchant entity that has one category entity in the list (as it should have, because there is only one category associated with merchant), but I also need all translations to be loaded for that category, and if possible, to do it with one query, i can solve it with two queries, but i would like it to be only one... or if there is a better reason to have two queries to extract data from database...?

clzola
  • 1,925
  • 3
  • 30
  • 49
  • Does this answer your question? [Should I include distinct in this JPQL query?](https://stackoverflow.com/questions/63410722/should-i-include-distinct-in-this-jpql-query) – crizzis Sep 27 '20 at 22:17

2 Answers2

0

Use @OneToMany(fetch = FetchType.LAZY) annotation with lazy fetch type method. A good post to read https://www.baeldung.com/hibernate-lazy-eager-loading.

Kayis Rahman
  • 352
  • 3
  • 13
  • I am using FetchType.LAZY everywhere, it is not problem that i do not want to load, the problem is hibernate duplicates categories... – clzola Sep 25 '20 at 12:51
0

The problem is that the categories attribute is a list. You need to use a Set instead

Christian Beikov
  • 15,141
  • 2
  • 32
  • 58