Spring Framework
Integrating JPA and Hibernate with Spring
Intermediate7 min readUpdated
Spring does not replace JPA; it wires it — the EntityManagerFactory, the transaction-bound EntityManager, exception translation and the persistence context lifecycle. After this guide you can set up Hibernate ORM 6 under Spring Framework 6 without a persistence.xml, understand what @PersistenceContext really injects, and recognise the persistence-context mistakes that cause LazyInitializationException, N+1 queries and lost updates.
What you will learn
- Configure LocalContainerEntityManagerFactoryBean and JpaTransactionManager in Java configuration
- Explain what the shared EntityManager proxy is and how it binds to a Spring transaction
- Write a repository with EntityManager and get DataAccessException translation for free
- Diagnose LazyInitializationException and N+1 selects and fix them with fetch joins or entity graphs
- Decide whether to enable Open EntityManager in View and understand its cost
Jakarta Persistence (JPA) defines the object-relational mapping API — entities, the EntityManager, JPQL, the Criteria API — and Hibernate ORM is the implementation almost everyone runs. Spring's role is narrower than newcomers expect: it does not map objects or generate SQL. It creates the EntityManagerFactory, hands each transaction its own EntityManager, translates persistence exceptions into its own hierarchy and manages the transaction that a JPA persistence context lives inside. Get those four things right and the JPA code you write is the same code you would write anywhere. This guide targets Spring Framework 6.x with Hibernate ORM 6 and the jakarta.persistence namespace on Java 17 or later; the Spring Data JPA repository layer that sits on top is covered in the Spring Boot subject.
Setting up the persistence unit in Java
The classic Java EE way is a persistence.xml naming a persistence unit, its classes and its provider. Under Spring you can skip the file and describe the unit as beans:
@Configuration
@EnableTransactionManagement
public class PersistenceConfig {
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
var emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource);
emf.setPackagesToScan("com.example.shop.domain"); // finds @Entity classes
emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
var props = new Properties();
props.put("hibernate.hbm2ddl.auto", "validate"); // never "update" in production
props.put("hibernate.jdbc.batch_size", "50");
props.put("hibernate.order_inserts", "true");
emf.setJpaProperties(props);
return emf;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
return new JpaTransactionManager(emf);
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
}
LocalContainerEntityManagerFactoryBean is a FactoryBean: the container exposes the product, an EntityManagerFactory, under the bean name, which is why the transaction manager method can ask for EntityManagerFactory directly. The "container" in the name refers to Spring acting as the JPA container — it performs the bootstrap that an application server would, including class-path scanning and, if a weaver is configured, load-time bytecode enhancement. The older LocalEntityManagerFactoryBean uses plain Persistence.createEntityManagerFactory and is only suitable for tests.
HibernateJpaVendorAdapter sets Hibernate-specific defaults and installs a HibernateJpaDialect, which is what lets JpaTransactionManager apply isolation levels, expose the underlying JDBC connection and translate Hibernate exceptions. Provider properties pass straight through setJpaProperties; hibernate.dialect is detected from the connection in Hibernate 6 and rarely needs setting.
The shared EntityManager
A JPA EntityManager is not thread-safe and represents one persistence context: a unit of work with its first-level cache of managed entities. In a container-managed setup you never create one yourself. Instead you inject a proxy:
@Repository
public class JpaProductRepository implements ProductRepository {
@PersistenceContext
private EntityManager em; // shared, thread-safe proxy
@Override
public Optional<Product> findBySku(String sku) {
return em.createQuery("select p from Product p where p.sku = :sku", Product.class)
.setParameter("sku", sku)
.getResultStream()
.findFirst();
}
@Override
public Product save(Product product) {
if (product.getId() == null) {
em.persist(product); // becomes managed; INSERT at flush
return product;
}
return em.merge(product); // copies state onto a managed instance; returns that instance
}
}
@PersistenceContext is processed by Spring's PersistenceAnnotationBeanPostProcessor, registered automatically by annotation-driven contexts. What it injects is a shared EntityManager proxy. On every method call the proxy looks for the EntityManager bound to the current Spring transaction on the current thread; if one exists, it delegates to it. If none exists, read operations get a short-lived EntityManager that is closed after the call, and write operations such as persist throw TransactionRequiredException. This is the mechanism that makes a repository with one injected field safe to use from every request thread, and it is also why the transaction must be started by Spring — a JPA em.getTransaction().begin() call on the proxy is rejected, because Spring owns the boundary.
The consequence for design: a persistence context lives exactly as long as the Spring transaction. Entities loaded inside a @Transactional service method are managed until that method returns and the transaction commits; after that they are detached, and touching an uninitialised lazy association throws LazyInitializationException.
@PersistenceContext works on fields and setters but not constructors. For constructor injection, declare a SharedEntityManagerBean in configuration and inject EntityManager normally — Spring Data JPA registers an equivalent bean automatically, which is why @Autowired EntityManager is common in Boot projects.
Transactions and the persistence context
JpaTransactionManager does for JPA what JdbcTransactionManager does for JDBC: on @Transactional entry it creates an EntityManager, begins a transaction on it, binds both to the thread, and on exit flushes, commits and closes. Because the EntityManager is bound to the thread, a JdbcTemplate using the same DataSource inside that transaction sees the same connection — the dialect exposes it — so mixing JPA for writes and JDBC for reporting queries in one transaction works and is a legitimate pattern.
@Service
public class CatalogService {
private final ProductRepository products;
private final PriceHistoryRepository history;
public CatalogService(ProductRepository products, PriceHistoryRepository history) {
this.products = products;
this.history = history;
}
@Transactional
public void reprice(String sku, Money newPrice) {
Product p = products.findBySku(sku).orElseThrow(() -> new UnknownSkuException(sku));
history.record(p, p.getPrice(), newPrice);
p.setPrice(newPrice); // no save() call: dirty checking issues the UPDATE at commit
}
@Transactional(readOnly = true)
public List<ProductSummary> summaries() {
return products.findSummaries();
}
}
The setPrice line with no explicit save is the defining habit of JPA under Spring: a managed entity is tracked, and at flush Hibernate compares its current state with the snapshot taken at load and emits the necessary UPDATE. Developers coming from JDBC often add a redundant em.merge(p), which is harmless for a managed entity but signals a misunderstanding.
readOnly = true is more than a hint here. JpaTransactionManager passes it to the Hibernate Session, which sets flush mode to MANUAL and marks loaded entities read-only, skipping snapshot creation and dirty checking. On a page that loads thousands of rows this is a measurable saving.
Exception translation
Hibernate throws jakarta.persistence.PersistenceException subclasses and its own HibernateException types. PersistenceExceptionTranslationPostProcessor wraps every @Repository bean in a proxy that converts those into Spring's DataAccessException hierarchy, so a service catches DataIntegrityViolationException from a JPA repository exactly as it would from a JDBC one, and OptimisticLockException surfaces as ObjectOptimisticLockingFailureException. Spring Boot registers this post-processor for you; in plain Framework configuration you declare it, as above. Note that exceptions thrown at commit — a deferred constraint violation, an optimistic-lock failure detected at flush — are translated by JpaTransactionManager itself, so they arrive translated even without the post-processor.
Lazy loading, N+1 and fetching strategies
JPA defaults @ManyToOne and @OneToOne to eager fetching and @OneToMany and @ManyToMany to lazy. Most experienced teams make everything lazy (fetch = FetchType.LAZY on the to-one associations too) and decide fetching per query, because an eager to-one association is loaded on every access of the parent whether it is needed or not, and eager loads multiply across nested associations.
Lazy associations create two failure modes:
LazyInitializationExceptionwhen an association is first touched after the persistence context closed — typically in a view template or in a JSON serialiser running after the service method returned.- N+1 selects when code iterates a list of N parents and touches a lazy association on each, producing one query for the list and N more for the children.
Both are fixed the same way: tell the query what you need.
// JPQL fetch join: one query, children initialised
List<Order> orders = em.createQuery("""
select distinct o from Order o
join fetch o.lines l
join fetch l.product
where o.customer.id = :customer
""", Order.class)
.setParameter("customer", customerId)
.getResultList();
// Entity graph: same effect, reusable and composable
EntityGraph<Order> graph = em.createEntityGraph(Order.class);
graph.addSubgraph("lines").addAttributeNodes("product");
List<Order> sameOrders = em.createQuery("select o from Order o where o.customer.id = :customer", Order.class)
.setParameter("customer", customerId)
.setHint("jakarta.persistence.fetchgraph", graph)
.getResultList();
Fetch-joining two collections in one query produces a Cartesian product and Hibernate 6 rejects it for bags; fetch one collection per query or use @BatchSize on the association so Hibernate loads children for many parents in IN (...) batches. For read-only screens, the cleanest answer is often not to load entities at all: a JPQL constructor expression — select new com.example.ProductSummary(p.sku, p.name, p.price) from Product p — returns exactly the columns the screen needs with no lazy proxies to trip over.
Open EntityManager in View
The Open EntityManager in View pattern (OpenEntityManagerInViewFilter or OpenEntityManagerInViewInterceptor in Spring MVC) keeps the persistence context open for the whole HTTP request, so lazy associations can still be initialised while a view template renders. It makes LazyInitializationException disappear, which is why Spring Boot enables it by default for web applications and logs a warning saying so.
The cost is real. Database connections are held for the duration of rendering, including any remote calls the view makes; N+1 queries become invisible because they work, just slowly; and the service layer's transaction boundary no longer defines what data the request can reach. For an application with a clear service layer and a REST API returning DTOs, turn it off and let the exception tell you where a query is incomplete. For a server-rendered application maintained by a small team it is a reasonable trade, provided someone watches the query counts.
Using Hibernate directly
Spring still ships native Hibernate support in spring-orm: LocalSessionFactoryBean builds a SessionFactory and HibernateTransactionManager drives it. In new code, prefer the JPA bootstrap above and drop to Hibernate only where JPA has no equivalent:
Session session = em.unwrap(Session.class);
Product p = session.byNaturalId(Product.class).using("sku", sku).load();
unwrap costs nothing and keeps the special case visible. HibernateTransactionManager remains useful in one scenario: a legacy application that already uses Session everywhere and cannot be rewritten at once — JpaTransactionManager can also expose the session via unwrap, so even then the JPA bootstrap is usually sufficient.
Common mistakes
Touching a lazy association after the transaction. Fetch it in the query, map to a DTO inside the service, or extend the transaction to cover the use — never enable Open EntityManager in View just to silence the exception without understanding the cost.
hibernate.hbm2ddl.auto=update in production. It cannot rename or drop safely, silently diverges from the intended schema and provides no history. Use a migration tool (Flyway or Liquibase) and set validate so startup fails on drift.
Eager to-one associations everywhere. Every load of an Order also loads its Customer, the customer's Address, and so on. Make associations lazy by default.
Calling save/merge in a loop on managed entities. Redundant. Modify the managed instance; Hibernate flushes the changes.
Forgetting @Version. Two users editing the same row last-write-wins silently. A @Version column turns the conflict into ObjectOptimisticLockingFailureException that the UI can handle.
Expecting em.persist to run the INSERT immediately. SQL is deferred to flush — at commit, before a query that needs consistent results, or on an explicit em.flush(). Generated identifiers using IDENTITY are the exception, because Hibernate must insert to learn the key, which also disables insert batching for that entity; prefer SEQUENCE.
Large transactions loading thousands of entities. The persistence context holds every managed entity until commit, and dirty checking scans all of them at flush. Process in chunks, clear() between chunks, or use a stateless session for bulk work.
Key takeaways
- Spring bootstraps JPA with
LocalContainerEntityManagerFactoryBeanand drives transactions withJpaTransactionManager; nopersistence.xmlis required. @PersistenceContextinjects a shared proxy that delegates to theEntityManagerbound to the current Spring transaction; writes outside a transaction fail by design.- The persistence context lives exactly as long as the transaction; managed entities are dirty-checked and flushed at commit, detached entities are not.
@RepositoryplusPersistenceExceptionTranslationPostProcessorgives the sameDataAccessExceptiontypes as JDBC.- Make associations lazy and fetch explicitly with fetch joins, entity graphs or DTO projections; that is the fix for both
LazyInitializationExceptionand N+1. - Open EntityManager in View trades connection-holding time and hidden query costs for convenience; decide consciously.
Sources and further reading
Frequently asked questions
- Do I still need a persistence.xml with Spring?
- No. LocalContainerEntityManagerFactoryBean can build the persistence unit entirely from Java configuration: you give it the DataSource, the packages to scan for @Entity classes and the vendor adapter, and pass provider properties through setJpaProperties. A persistence.xml is still honoured if present, which is useful when migrating from a Jakarta EE application server.
- What is the difference between @PersistenceContext and @Autowired EntityManager?
- @PersistenceContext is handled by Spring's PersistenceAnnotationBeanPostProcessor and injects a thread-safe shared proxy that delegates to the transaction-bound EntityManager. Plain @Autowired only works if a bean of type EntityManager exists; Spring Data JPA registers such a shared proxy bean, which is why the two look interchangeable in Spring Boot projects. In a plain Spring Framework application, use @PersistenceContext or declare a SharedEntityManagerBean yourself.
- Why do I get 'No EntityManager with actual transaction available' on persist?
- The shared EntityManager proxy requires an active Spring-managed transaction for write operations, because outside one there is no persistence context to hold the entity until flush. Annotate the calling service method with @Transactional and make sure the call arrives through the proxy — not by self-invocation — and that @EnableTransactionManagement is present.
- Should I use Hibernate's Session API or JPA's EntityManager?
- Code against EntityManager and JPQL wherever possible; it keeps the persistence layer portable and matches Spring Data JPA and every current tutorial. When you need a Hibernate-only feature such as StatelessSession, natural-id lookups or filters, call entityManager.unwrap(Session.class) at that one spot rather than configuring the native SessionFactory globally.