ORM frameworks like Hibernate and other JPA implementors can significantly simplify development of persistence layer. Introducing entity abstraction level helps to model clean business domain and to hide underlying SQL statements used to achieve persistence of the domain. Such approach is especially useful in large domains, since developer no longer needs to create and maintain all SQL statements used by application.

Just a few JPA annotations like

@Entity /@ManyToOne /@OneToMany etc. on the domain classes and EntityManager or custom repositories to obtain domain aggregate roots, and you are ready to go. Having that, the vast majority of use cases involving persistence can be handled in domain model by JPA cascades and traversing associations and performing operations on them.

Everything comes with a price. In exchange for clean and easy development, some issues can arise sooner or later:

  • Large amount of SQL statements issued by excessive lady-loading i.e. due to N+1 SELECT problem
  • Eager fetches performed in inefficient way (i.e fetchType = FetchType.EAGER on associations)
  • No easy way to list all SQL statements invoked across some use case / service call and to correlate them with exact lines of code
  • Even if for some use case fetching had been optimized to load all necessary data in efficient way, future change in code can silently break it, and there is no way easy to prevent it.

In next steps I’ll show the new approach how these problems could be detected, but first let’s see to classic way.

#java #jpa #sql #spring-boot #performance #lazy-loading #jplusone #hibernate

How To Find Origin And Context of JPA For Issued SQL Statements
1.30 GEEK