hibernatejava-8spring-data-jpaspring-boot-2

JPA joins retrieve lots of permutations


I have an entity with lots of joins. Following is a stripped down version of it.

@Entity
@Table(name = "NEWS")
public class NewsV2 {

    @Fetch(FetchMode.JOIN)
    @OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
    @JoinColumn(name = "NEWS_ID", referencedColumnName = "NEWS_ID")
    private Set<NewsDetails> newsDetails;

    @Fetch(FetchMode.JOIN)
    @OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
    @JoinColumn(name = "NEWS_ID", referencedColumnName = "NEWS_ID")
    private Set<NewsCountries> newsCountries;

    @Fetch(FetchMode.JOIN)
    @OneToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH, CascadeType.DETACH})
    @JoinColumns({@JoinColumn(name = "EXT_ID", referencedColumnName = "EXT_ID", insertable = false, updatable = false), @JoinColumn(name = "EXT_CODE", referencedColumnName = "EXT_CODE", insertable = false, updatable = false),})
    private Set<NewsFiles> newsFiles;
}

I have only shown 3 joins here. There are almost 20 such attributes with joins, plus lots of other attributes. The issue I'm facing is when retrieving a news, it fetches all the different permutations that ultimately cause high memory load and crash the application.

For example, for same news if 2 countries are there (say US and UK), then same news is repeated twice when fetching. Now imagine 20 such joins with all different permutations among them. I am getting 5000 rows for a single id.

What I want is to populate just the countries associated with the entity, without going over all the joins and what not.

Lazy loading is not a possibility because I need all the associated entities. I have tried @Subselect, @Formula but those are all read-only. @ColumnTransformer is there but it seems it can only do simple transformations. I cannot populate another table when trying to write nor fetch from another table (or can I? If it's possible please show me an example)

Is there any other way other than above?


Solution

  • Lazy loading is not a possibility because I need all the associated entities.

    That is wrong. Lazy loading is not only a possibility it is the solution to your problem. It is understood that you need those associated entities and Lazy loading will load them for you.

    You can not efficiently load multiple 1:M or N:M relationships eagerly with JPA/Hibernate.