Skip links

Spring Data JPA: Data Access Enhancement

Jump To Section

Spring Data JPA

Exploring Revolutionary Spring Data JPA Optimization Strategies

Spring Data JPA improves the implementation of JPA-based repositories. Such a module is related to extended support for JPA-based data access layers. It makes building applications that use Spring-powered data access technologies much easier.
Thus, the goal of Spring Data JPA is to significantly enhance the implementation process of data access layers through reducing the effort to the amount really needed.

In our short guideline, we will show the optimization cases of specific examples without unnecessarily long descriptions. You will also be provided with the scripts with the given solutions for discussed framework/library. The simpler, the better.

Spring data jpa

Process Playlist Method

  • The case: unwanted changes saved in DB

The main task of the ProcessPlaylist method is to extract data from the request and save them in the database. It is possible that something bad and unexpected happens before the method ends. What should be done in such a case? Do we want to have some data saved in the DB? In most cases, the answer is NO. There is no guarantee that the data is consistent. All changes to the DB should be rollbacked.

Also read: Modeling money in Java: Pitfalls and Solutions

Optimizing JAVA

Fix: trigger rollback with Transactional annotation

One of the easiest ways to add rollback support for a failed flow is the Transactional annotation. For each exception thrown, all DB changes made to the method will be rolled back. This is the default behavior. The Transactional annotation has many properties, including propagation, isolation, timeout, rollbackFor. There are many options for configuring DB transactions.

ProcessPlaylist Method
  • The case: “safe” change with side effects

It is not always easy to find an error related to the DB operation. In this case, one action (addSongs) was moved after calling saveAll. Existing tests will still pass (unit tests, functional tests, regression tests, e2e), as there is no change in the application’s behavior. We are not aware of anything wrong that could happen.

Trigger rollback with Transactional annotation

Action: activate SQL logging

To be able to see the generated SQL queries you need to add new entries in the configuration. This should be activated only in the development environment. In production, this is not needed.
The generated queries are now visible in the logs. The number of queries and their correctness can be verified.

activate SQL logging

Fix: call addSongs() before saveAll()

Adding SQL logging helped us find a performance problem (an additional UPDATE statement for each track). This example was trivial. In more complex code, it is difficult to see these types of problems without SQL logging.

Adding SQL logging

Operations performed on the target object are propagated to the related object

In some cases, we want a tighter connection between entities. Adding a cascade parameter in the OneToMany annotation can help with this. Operations performed on the target entity are propagated to the associated entity. Fewer repository calls are needed to achieve the same result. The risk of forgetting to update or delete a related entity is reduced.
In this example, the save method is called only on the playlist entity. By using cascading, the songs will also be saved.

multiple UPDATE DB calls for a simple task
  • The case: multiple UPDATE DB calls for a simple task

Very often we don’t think about performance when we add new functionality to an application. If you are a Java programmer, you want to write code in Java. This is generally fine, but in some cases moving easy-to-implement business logic to SQL may be worth considering.
In the updateSongs method presented, a new UPDATE statement will be executed for each song.

multiple UPDATE DB calls for a simple task

Fix: use SQL/JPQL for simple task

The same functionality can be achieved with a simple SQL/JPQL query. The code is still quite easy to understand and has better performance. Only one UPDATE statement will be generated here.

SQL/JPQL for simple task
  • The case: h2 in memory DB has better performance

All the previously presented Postman calls had very low execution times. The main reason for this is the use of the h2 database. It is an In-Memory database, so the latency is lower. To see how the disk database behaves, we switched to Oracle DB.

h2 in memory DB has better performance

Fix: activate hibernate batching

A significant increase in productivity can be achieved by enabling hibernate batching. The batch size parameter may not be so easy to estimate. You need some information about the size of the data being processed. The Generate_statistics property can help analyze performance for different batch sizes.

additional SELECT for each Playlist
  • The case: additional SELECT for each Playlist

The N+1 query problem occurs when the data access framework makes N additional SQL calls to fetch the same data that could have been retrieved when the main SQL query was executed.
In the current configuration, the findAllSongs method would generate one SELECT query to get all the playlists and N additional SELECTS to get the songs for each playlist found.

SELECT query - JPA

Fix: add Fetch annotation

Adding the Fetch annotation is a quick solution to the “N + 1” problem. It’s not perfect because 2 SELECT statements will be generated to get all the pieces, but it’s still better than N + 1.

SELECT statements -JPA

Summary

So that’s it. We collected the cases with suggestions for fixing them. If you have any experience with the Spring Data JPA library, it would be nice if you share in the comments! Please visit our blog, where there is not only a lot about programming, but also a lot of other technical and IT-related topics. Something new again soon!

The material was created in collaboration between Senior Engineer — Dariusz Tomczyk (Altimetrik Poland) and Content Writer — 

Kinga Kuśnierz (Altimetrik Poland) based on materials from a webinar Dariusz recently hosted.

Original Article here >

Picture of Dariusz Tomczyk

Dariusz Tomczyk

Suggested Reading

Ready to Unlock Your Enterprise's Full Potential?

Michael Woodall

Chief Growth Officer of Financial Services

Michael Woodall, as the Chief Growth Officer of Financial Services at Altimetrik, spearheads the identification of new growth avenues and revenue streams within the financial services sector. With a robust background and extensive expertise, Michael brings invaluable insights to his role.

Previously, Michael served as the Chief of Operations and President of the Trust Company at Putnam Investments, where he orchestrated strategic developments and continuous operational enhancements. Leveraging strategic partnerships and data analytics, he revolutionized capabilities across investments, retail and institutional distribution, and client services. Under his leadership, Putnam received numerous accolades, including the DALBAR Mutual Fund Service Award for over 30 consecutive years.

Michael’s dedication to industry evolution is evident through his involvement with prestigious organizations such as the DTCC Senior Wealth Advisory Board, ICI Operations Committee, and NICSA, where he served as Chairman and now holds the position of Director Emeritus. Widely recognized as an industry luminary, Michael frequently shares his expertise with various divisions of the SEC, solidifying his reputation as a seasoned presenter.

At Altimetrik, Michael plays a pivotal role in driving expansion within financial services, leveraging his expertise and Altimetrik’s Digital Business Methodology to ensure clients navigate their digital journey seamlessly, achieving tangible outcomes and exponential growth.

Beyond his corporate roles, Michael serves as Chair of the Boston Water & Sewer Commission, appointed by the Mayor of Boston, and is actively involved in various philanthropic endeavors, including serving on the board of the nonprofit Inspire Arts & Music.

Michael holds a distinguished business degree from Northeastern University, graduating with distinction as a member of the Sigma Epsilon Rho Honor Society.

Anguraj Kumar Arumugam

Chief Digital Business Officer for the U.S. West region

Anguraj is an accomplished business executive with an extensive leadership experience in the services industry and strong background across digital transformation, engineering services, data and analytics, cloud and consulting.

Prior to joining Altimetrik, Anguraj has served in various positions and roles at Globant, GlobalLogic, Wipro and TechMahindra. Over his 25 years career, he has led many strategic and large-scale digital engineering and transformation programs for some of world’s best-known brands. His clients represent a range of industry sectors including Automotive, Technology and Software Platforms. Anguraj has built and guided all-star teams throughout his tenure, bringing together the best of the techno-functional capabilities to address critical client challenges and deliver value.

Anguraj holds a bachelor’s degree in mechanical engineering from Anna University and a master’s degree in software systems from Birla Institute of Technology, Pilani.

In his spare time, he enjoys long walks, hiking, gardening, and listening to music.

Vikas Krishan

Chief Digital Business Officer and Head of the EMEA region

Vikas (Vik) Krishan serves as the Chief Digital Business Officer and Head of the EMEA region for Altimetrik. He is responsible for leading and growing the company’s presence across new and existing client relationships within the region.

Vik is a seasoned executive and brings over 25 years of global experience in Financial Services, Digital, Management Consulting, Pre- and Post-deal services and large/ strategic transformational programmes, gained in a variety of senior global leadership roles at firms such as Globant, HCL, Wipro, Logica and EDS and started his career within Investment Banking. He has developed significant cross industry experience across a wide variety of verticals, with a particular focus on working with and advising the C-Suite of Financial Institutions, Private Equity firms and FinTech’s on strategy and growth, operational excellence, performance improvement and digital adoption.

He has served as the engagement lead on multiple global transactions to enable the orchestration of business, technology, and operational change to drive growth and client retention.

Vik, who is based in London, serves as a trustee for the Burma Star Memorial Fund, is a keen photographer and an avid sportsman.

Megan Farrell Herrmanns

Chief Digital Officer, US Central

Megan is a senior business executive with a passion for empowering customers to reach their highest potential. She has depth and breadth of experience working across large enterprise and commercial customers, and across technical and industry domains. With a track record of driving measurable results, she develops trusted relationships with client executives to drive organizational growth, unlock business value, and internalize the use of digital business as a differentiator.

At Altimetrik, Megan is responsible for expanding client relationships and developing new business opportunities in the US Central region. Her focus is on digital business and utilizing her experience to create high growth opportunities for clients. Moreover, she leads the company’s efforts in cultivating and enhancing our partnership with Salesforce, strategically positioning our business to capitalize on new business opportunities.

Prior to Altimetrik, Megan spent 10 years leading Customer Success at Salesforce, helping customers maximize the value of their investments across their technology stack. Prior to Salesforce, Megan spent over 15 years with Accenture, leading large transformational projects for enterprise customers.

Megan earned a Bachelor of Science in Mechanical Engineering from Marquette University. Beyond work, Megan enjoys playing sand volleyball, traveling, watching her kids soccer games, and is actively involved in a philanthropy (Advisory Council for Cradles to Crayons).

Adaptive Clinical Trial Designs: Modify trials based on interim results for faster identification of effective drugs.Identify effective drugs faster with data analytics and machine learning algorithms to analyze interim trial results and modify.
Real-World Evidence (RWE) Integration: Supplement trial data with real-world insights for drug effectiveness and safety.Supplement trial data with real-world insights for drug effectiveness and safety.
Biomarker Identification and Validation: Validate biomarkers predicting treatment response for targeted therapies.Utilize bioinformatics and computational biology to validate biomarkers predicting treatment response for targeted therapies.
Collaborative Clinical Research Networks: Establish networks for better patient recruitment and data sharing.Leverage cloud-based platforms and collaborative software to establish networks for better patient recruitment and data sharing.
Master Protocols and Basket Trials: Evaluate multiple drugs in one trial for efficient drug development.Implement electronic data capture systems and digital platforms to efficiently manage and evaluate multiple drugs or drug combinations within a single trial, enabling more streamlined drug development
Remote and Decentralized Trials: Embrace virtual trials for broader patient participation.Embrace telemedicine, virtual monitoring, and digital health tools to conduct remote and decentralized trials, allowing patients to participate from home and reducing the need for frequent in-person visits
Patient-Centric Trials: Design trials with patient needs in mind for better recruitment and retention.Develop patient-centric mobile apps and web portals that provide trial information, virtual support groups, and patient-reported outcome tracking to enhance patient engagement, recruitment, and retention
Regulatory Engagement and Expedited Review Pathways: Engage regulators early for faster approvals.Utilize digital communication tools to engage regulatory agencies early in the drug development process, enabling faster feedback and exploration of expedited review pathways for accelerated approvals
Companion Diagnostics Development: Develop diagnostics for targeted recruitment and personalized treatment.Implement bioinformatics and genomics technologies to develop companion diagnostics that can identify patient subpopulations likely to benefit from the drug, aiding in targeted recruitment and personalized treatment
Data Standardization and Interoperability: Ensure seamless data exchange among research sites.Utilize interoperable electronic health record systems and health data standards to ensure seamless data exchange among different research sites, promoting efficient data aggregation and analysis
Use of AI and Predictive Analytics: Apply AI for drug candidate identification and data analysis.Leverage AI algorithms and predictive analytics to analyze large datasets, identify potential drug candidates, optimize trial designs, and predict treatment outcomes, accelerating the drug development process
R&D Investments: Improve the drug or expand indicationsUtilize computational modelling and simulation techniques to accelerate drug discovery and optimize drug development processes