I initially started of solving a N+1 select issue in my @OneToOne mapping scenario, i finally was able to reduce the multiple select queries to one. I tried using EntityGraphs to resolve the N+1 issue, but it does not work. So i changed my @OneToOne mapping to LAZY, by setting the fetch Type to Lazy and setting Optional=false. I am using Hibernate JPA.
I made changes as shown below
Public Class Parent {
@OneToOne(
optional = false,
mappedBy = "parent",
fetch = FetchType.LAZY,
cascade = {CascadeType.ALL})
@NotFound
private Child child;
}
In My Child class,
Public Class Child {
@Id
private String Id;
@OneToOne
@PrimaryKeyJoinColumn
private Parent parent;
}
The Repository class is as below ,
public interface ParentChildRepository extends PagingAndSortingRepository<Transaction, String> {
@EntityGraph(value = "Parent.EntityGraph", type = EntityGraphType.LOAD)
default List<Transaction> findall() {
return StreamSupport.stream(findAll().spliterator(), false).collect(Collectors.toList());
}
}
Without the optional = false, LazyLoading does not work and i get N+1 Select query statements, but when i do set optional = false, EntityNotFoundException exception is thrown. The EntityNotFoundException is not thrown when the optional=false statement is removed/set to true, but it doesn't fix my N+1 select issue.
Please provide some suggestions.