DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How Spring Security Concurrent Session Control Works: Part 1
  • Integrating Twilio Into My SaaS Solution In Heroku
  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  • How Spring and Hibernate Simplify Web and Database Management

Trending

  • The Future of Java and AI: Coding in 2025
  • Beyond Code Coverage: A Risk-Driven Revolution in Software Testing With Machine Learning
  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  • Agentic AI for Automated Application Security and Vulnerability Management
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring and PersistenceContextType.EXTENDED

Spring and PersistenceContextType.EXTENDED

By 
Bozhidar Bozhanov user avatar
Bozhidar Bozhanov
·
Sep. 13, 11 · Interview
Likes (18)
Comment
Save
Tweet
Share
13.3K Views

Join the DZone community and get the full member experience.

Join For Free

Recently I was introduced to a project that’s already 4 months in development. After a day of coding I realized there’s something wrong with the session and transaction management. Then I found something that I’ve never used and didn’t quite know when it should be used – the EntityManager was injected into DAO objects via @PersistenceContext(type=PersistenceContextType.EXTENDED)

First thing to do – google. Found this spring forum discussion, which made it clearer, but not quite.

Then I started debugging and realized that the application is de-facto using the session-per-application anti-pattern. Not only that, but each DAO got its own entity manager (and underlying session) instance.

An important note here – I say “entity manager and underlying session”, because Hibernate simply wraps its Session with an implementation of the standard EntityManager interface. So it makes a little difference whether we talk about entity manager or session.

What happens? PerssitenceContextType.EXTENDED means that you, rather than spring, are in charge of managing your session. All spring does is create it on startup and close it on shutdown. The other option (which is the default – PerssitenceContextType.TRANSACTION) lets spring’s transaction managers create the entity manager (and session) for each request, start a transaction, and when you are finished – commit the transaction and close the session.

This is called session and transaction management, and it is one of the most important things to do in a spring & JPA project. It should be done right almost from the start, so the next time you do such a project, spend extra days to get this right.

But what is wrong with the above situation? Here are some effects of the extended manager:

  • Each DAO gets a different instance of the EntityManager so you can’t do any meaningful work that involves two DAOs. If you insert a records with one EntityManager and try to use it in another one – it won’t work. The first hasn’t been flushed, and the second does not have the 1st level cache.
  • If a session does not get closed it accumulates entities (it stores them in memory so that it doesn’t have to fetch them multiple times from the DB). Which is a pure memory leak.
  • It is not thread-safe. The Session and EntityManager objects are not thread-safe. Since you are most likely to inject them in a singleton DAO object you will start getting weird results due to concurrent access

How did this happen and why it got unnoticed for so long? I have a theory. 1. People started using the DAO layer directly from the web layer 2. Something wasn’t working for someone, so he changed the type of the persistence context, which made his code work. 3. As the project is not having many inserts, people were mainly reading data and didn’t stumble upon the various problems. 4. There hasn’t been extensive testing, with multiple people on the same instance, so the concurrency problems were not spotted.

One more thing – PersistenceContextType.EXTENDED is useful in limited scenarios. The so called long-running session or session-per-conversation. When you have wizards you can have multiple requests with the same session, which saves some detaching and merging. But should you use that, make sure you don’t do it for the whole application and that you are absolutely know what you are doing. And close the session when the conversation ends. Another scenario is usage in EJB stateful beans. (In general, the extended persistence context makes more sense in a JavaEE environment)

So to summarize:

  • Spend a lot of time to properly configure session and transaction management and try to get it right
  • Almost never use PersistenceContextType.EXTENDED in spring (outside a JavaEE container at least)
  • Don’t use the DAO layer directly from the web layer. A base service class with wrappers for the most used operations would not be too verbose, but will save you countless headaches
  • Code reviews should be thorough, or commit rights to core classes and configurations should be limited to a number of people that know what they are doing

 

From http://techblog.bozho.net/?p=417

Spring Framework Session (web analytics)

Opinions expressed by DZone contributors are their own.

Related

  • How Spring Security Concurrent Session Control Works: Part 1
  • Integrating Twilio Into My SaaS Solution In Heroku
  • Cookies Revisited: A Networking Solution for Third-Party Cookies
  • How Spring and Hibernate Simplify Web and Database Management

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!