0

I am new and currently created 2 entities. I have established onetomany - manytoone relationship but when I trying to see the sql queries run by hibernate it makes multiple query for the manytoone relationship. Below is the code snippet I have tried.

@Entity
@Data
@NoArgsConstructor
@Table(name = "claim")
@AllArgsConstructor
public class Claim {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  private String name;

  @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
  @JoinColumn(name = "claim_id", nullable = false)
  private List<Item> items;

}



@Data
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "items")
public class Item {
  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @JsonIgnore
  @ManyToOne(fetch = FetchType.EAGER)
  @JoinColumn(name = "claim_id", insertable = false, updatable = false)
  private Claim claim;

  private String name;
}

@Repository
public interface ClaimSqlRepository extends PagingAndSortingRepository<Claim, Long>, JpaSpecificationExecutor<Claim> {
}

@RequestMapping("/claims")
  @ResponseBody
  public Page<Claim> getClaims(
      Pageable pageable
  ) {
 Page<Claim> page = ClaimSqlRepository.findAll(pageable);
}

After I have a GET request and then I check the terminal there are multiple queries executed for item. I have already seen quite a many post but still not able to find the issue. My Repository implements PagingAndSortingRepository and JpaSpecificationExecutor. I am making a findAll call for the same. Below is similar to what I have seen in sql-show for Hibernate.

Hibernate: select claim0_.id as id1_0_ from claims claim0_ where 1=1 limit ?

Hibernate: select items0_.claim_id as clai4_1_0_, items0_.id as id1_1_0_ from items items0_ where items0_.claim_id=?

Hibernate: select items0_.claim_id as clai4_1_0_, items0_.id as id1_1_0_ from items items0_ where items0_.claim_id=?

Hibernate: select items0_.claim_id as clai4_1_0_, items0_.id as id1_1_0_ from items items0_ where items0_.claim_id=?
  • When you use JPA you turn over the implementation to JPA to do the queries. This may result in performance problems, but you are generally able to write less code, code faster and have more maintainable code. If you have performance problems you would need to use native queries or JDBC directly, etc. – DCTID Apr 15 '20 at 02:28
  • Please show us, what code you are executing and what SQL statements you see as a result and what kind of SQL statement you want to see as a result. Side note: Lazy loading isn't a remedy for the N+1 problem, it is part of the cause. – Jens Schauder Apr 15 '20 at 07:39
  • I have updated the question. Please have a look. @JensSchauder – Krish Jagratbhai Mehta Apr 15 '20 at 14:19
  • change the fetch type to `FetchType.EAGER` – Jens Schauder Apr 15 '20 at 14:57
  • @JensSchauder Its still not working – Krish Jagratbhai Mehta Apr 15 '20 at 15:01

0 Answers0