0

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.

Abi
  • 1
  • 3

2 Answers2

2

Try to use not found ignore like below.

@NotFound(action = NotFoundAction.IGNORE)

Refer this

Alien
  • 15,141
  • 6
  • 37
  • 57
  • Hello @Alien i tried the above annotation on my Parent Class. This does not work and i get the same error as before. javax.persistence.EntityNotFoundException. Unable to find Model.Child with id – Abi Oct 29 '18 at 13:12
  • I was able to resolve the above exception by posting the missing child entity information in the payload and then tried retrieving it.I understood that above error was valid and it was my mistake of setting the optional = false in the @OneToOne Lazy fetch. In my scenario in my child entity class, nulls are possible, so when i set optinal=false, i inform hibernate to generate a proxy (affirming nulls are impossible, even though its not). Still i am unsure why Bidirectional One to One mapping generates N+1 selects, even with Lazy or Eager fetching. – Abi Oct 29 '18 at 18:21
0

It worked with

@OneToOne(fetch = FetchType.LAZY)
@NotFound(action = NotFoundAction.IGNORE)
@LazyToOne(LazyToOneOption.NO_PROXY)

taken from here

Charlo Poitras
  • 198
  • 1
  • 14