Bypassing ORM relationships returns duplicate results

I have 4 tables - store, catalog_galleries, catalog_images, and catalog_financials .

When I cross relations from store --> catalog_galleries --> catalog_images other words: store.getCatalogGallery().getCatalogImages() I get duplicate entries. Does anyone know what could be causing this? Any suggestions on where to look?

The store table has OneToOne related to catalog_galleries , which in turn has OneToMany related to catalog_images and the type of impatient selection. The store table also relates to OneToMany catalog_financials .

The following are the relevant objects:

Save Object

 @Entity @Table(name="store") public class Store { ... private CatalogGallery gallery; ... @OneToOne(mappedBy="store") public CatalogGallery getGallery() { return gallery; } } 

CatalogGallery Element

 @Entity @Table(name="catalog_galleries") public class CatalogGallery { ... private Store store; private Collection<CatalogImage> catalogImages; ... @OneToOne @PrimaryKeyJoinColumn public Store getStore() { return store; } @OneToMany(mappedBy="catalogGallery", fetch=FetchType.EAGER) public Collection<CatalogImage> getCatalogImages { return catalogImages; } } 

CatalogImage Object

 @Entity @Table(name="catalog_images") public class CatalogImage { ... private CatalogGallery catalogGallery; ... @ManyToOne @JoinColumn(name="gallery_id", insertable=false, updatable=false) public CatalogGallery getCatalogGallery() { return catalogGallery; } } 
+4
source share
3 answers

This is because of your fetch = FetchType.EAGER .
Hibernate creates JOINs and tries to get all your collections with a single request.
If you really need FetchType.EAGER and you don't want to replace your collection with Set, you can use the @Fetch (FetchMode.SELECT) annotation @Fetch (FetchMode.SELECT) for your collection:

 @OneToMany(mappedBy="catalogGallery", fetch=FetchType.EAGER) @Fetch (FetchMode.SELECT) public Collection<CatalogImage> getCatalogImages { return catalogImages; } 

For more information see this post.

+5
source

If you implement the equals and hashcode methods correctly and store them in a collection, not a collection, this is less of a problem if the volume of duplicates is not excessive.

0
source
  • Your getter catalogImages() does not comply with the Java Bean naming convention. I'm not sure, but this can be a bit confusing for the JPA provider.
  • Using Collection<CatalogImage> , you explicitly told the JPA provider that duplicates are allowed . As already mentioned, using Set instead of Collection solves the problem of duplicates in most cases and avoids FetchType.EAGER if you really don't need it.
0
source

Source: https://habr.com/ru/post/1334592/


All Articles