I have a Product entity. One product can be a child of another. The relationship is mapped with OneToMany as follows.
@OneToMany(mappedBy = "parentProd")
private Set<Products> childProd = new HashSet<>();
@ManyToOne
@JsonIgnoreProperties("childProd")
private Products parentProd;
The parent_product_id column generated from this mapping somehow contains invalid parent_ids. Hence I am getting the following error when i try to query all products using JPA criteria query.
javax.persistence.EntityNotFoundException: Unable to find com.test.Products with id 101 at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$JpaEntityNotFoundDelegate.handleEntityNotFound(EntityManagerFactoryBuilderImpl.java:162) at org.hibernate.event.internal.DefaultLoadEventListener.load(DefaultLoadEventListener.java:234)
How to write a criteria query to select all Product entities without considering the parent_child relation?
@Entity
@Table(name = "products")
public class Products implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "productName")
private String productName;
@OneToMany(mappedBy = "parentProd")
private Set<Products> childProd = new HashSet<>();
@ManyToOne
@JsonIgnoreProperties("childProd")
private Products parentProd;
//Getters And Setters
}
CodePudding user response:
Change the oneToMany annotation this way:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "parentProd")
Here fetch = FetchType.Lazy means that data will not be fetched if you don't ask it explicitly.