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=?