0

I have a Controller from rest service that I call a Hibernate method to get the result, but I really don't know why the children components didn't come. When I call this method using Junit, It works. This is the Code:

{

@Entity
public class Product implements Serializable {
    private static final long serialVersionUID = -6131311050358241535L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column(nullable = false)
    private String name;

    private String description;


    @OneToMany(mappedBy = "product")
    private List<Image> images = new ArrayList<Image>();
}


{

@Entity
public class Image implements Serializable {

    private static final long serialVersionUID = 2128787860415180858L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @JoinColumn(name = "product_id")
    @ManyToOne
    private Product product;

    private ImageType type;
}
{

@PersistenceContext
private EntityManager entityManager;

public List<Product> findAllWithParentProductsAndImage() {
String hpql = "select distinct p from Product p left join fetch p.images";
List<Product> resultList = entityManager.createQuery(hpql, 
        Product.class).getResultList();
return resultList;
}
}

2 Answers2

1

By default @OneToMany will load lazily. You should use @OneToMany( mappedBy = "product", fetch=FetchType.Eager ) to do Eager fetch

0

You can definitely use

@OneToMany(mappedBy = "product", fetch=FetchType.Eager)

However this has a downside. You will always be fetching children even if you only want the Parent and its few properties.

Use JOIN FETCH within your @Query if you are using JpaRepositories.

Check out the following related questions

Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78