0

Iam working on web spring + hibernate project I have a problem in my loading set

I have a java class Entity

@Entity
public class Product 
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @ManyToMany(cascade= CascadeType.ALL)
    @JoinTable(
            joinColumns = @JoinColumn( name="parent_id"),
            inverseJoinColumns = @JoinColumn( name="id"))
    private Set<Product> gifts;

@ManyToMany(cascade= CascadeType.ALL)
    @JoinTable(
            joinColumns = @JoinColumn( name="parent_id"),
            inverseJoinColumns = @JoinColumn( name="id"))
    private Set<Product> suggestion;

@ManyToMany(cascade= CascadeType.ALL)
    @JoinTable(
            joinColumns = @JoinColumn( name="parent_id"),
            inverseJoinColumns = @JoinColumn( name="id"))
    Private Set<Product> relative;
}

gifts,suggestion and relative set are fetch = lazy and i dont want to eager

Now I want to Load gifts,suggestion and relative product in one statement hibernate query

whats the best suggest for my idea

i can not change source code i want to find way to load set objects when load product

1 Answers1

0

You can create an entity graph and fetch the graph whenever you need to eagerly fetch the associations.

1.First declare entity graph over Product entity.

@Entity
@NamedEntityGraph(name = "products",
attributeNodes = {@NamedAttributeNode("gifts"),
  @NamedAttributeNode("suggestion"),
  @NamedAttributeNode("relative")})
public class Product
{
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(name = "name")
    private String name;

    @ManyToMany(cascade= CascadeType.ALL)
    @JoinTable(
            joinColumns = @JoinColumn( name="parent_id"),
            inverseJoinColumns = @JoinColumn( name="id"))
    private java.util.Set<Product> gifts;

    @ManyToMany(cascade= CascadeType.ALL)
    @JoinTable(
            joinColumns = @JoinColumn( name="parent_id"),
            inverseJoinColumns = @JoinColumn( name="id"))
    private Set<Product> suggestion;

    @ManyToMany(cascade= CascadeType.ALL)
    @JoinTable(
            joinColumns = @JoinColumn( name="parent_id"),
            inverseJoinColumns = @JoinColumn( name="id"))
    private Set<Product> relative;
}

2.Then attach the graph to one of the repository method.

public interface ProductRepository extends JpaRepository<Product, Integer> {
        @EntityGraph(value = "products")
        Optional<Product> findById(Integer id);
    }

NOTE: all the associations you declare in EntityGraph attribute nodes will be loaded eagerly and those associations in Product which are not attribute node will still be fetched lazily.

Read difference between LOAD and FETCH Type:LOAD Vs FETCH

Mohd Waseem
  • 1,244
  • 2
  • 15
  • 36