Skip to content
javahacks.dev
JavaServer Faces

How to Integrate JSF With JPA and Transactions Safely

Use JPA safely from JSF: where to put transactions, injecting EntityManager into CDI services, avoiding lazy loading errors and handling optimistic locking.

6 min read
Summarize in AI
Flat illustration of a browser page built from server-side components, with the Hibernate, Spring, Vaadin and HTML5 logos.

A JSF request goes through six phases, and a managed bean's methods are called at several of them. A database call placed carelessly in a getter runs many times a page. A transaction left open across phases locks rows while the user thinks. The way out is a thin bean and a service layer with clear transaction boundaries. This uses Jakarta EE 10 or 11, Hibernate 7 and JDK 25. The phases are in the lifecycle.

The service owns the transaction

java
@ApplicationScoped
public class CustomerService {

    @PersistenceContext
    private EntityManager em;

    @Transactional
    public List<Customer> search(String name) {
        return em.createQuery(
                "select c from Customer c left join fetch c.addresses where lower(c.name) like :n",
                Customer.class)
            .setParameter("n", name.toLowerCase() + "%")
            .getResultList();
    }

    @Transactional
    public Customer save(Customer c) {
        return em.merge(c);
    }
}

The @Transactional interceptor opens a transaction on entry and commits on exit, so the persistence context lives and dies within the call. The query uses a fetch join so the addresses are loaded before the entities are detached. For an EJB container, @Stateless services do the same job. The semantics of transaction types are in Jakarta Transactions.

The bean stays thin

java
@Named
@ViewScoped
public class CustomerBean implements Serializable {

    @Inject CustomerService service;

    private String filter = "";
    private List<Customer> customers = List.of();
    private Customer selected;

    public void search() { customers = service.search(filter); }

    public void save() {
        try {
            selected = service.save(selected);
            search();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Saved"));
        } catch (OptimisticLockException e) {
            FacesContext.getCurrentInstance().addMessage(null,
                new FacesMessage(FacesMessage.SEVERITY_WARN, "Changed by someone else", "Reload and retry"));
        }
    }
    // getters and setters
}

The bean holds data in fields and loads it on an action, not in a getter. A view scoped bean keeps selected between AJAX requests, see bean scopes. selected is detached because the service transaction ended, so merge re-attaches the changes on save. Using persist on a detached entity gives the error described in detached entity passed to persist.

Lazy loading problems

Rendering a page that touches a lazy collection after the transaction ended throws LazyInitializationException, covered in that fix. Choices, in order of preference:

  1. Load what the page needs with a fetch join or entity graph in the service method.
  2. Return a DTO or projection tailored to the page.
  3. Initialise the collection inside the service method.

Avoid a request-wide transaction filter ("open session in view") that keeps the session open during rendering. It hides N+1 queries inside EL expressions and holds a database connection while the page renders, an anti-pattern in JSF where rendering calls the same getter repeatedly.

Lazy data tables

For large tables use PrimeFaces' LazyDataModel and have load call a service method that applies the offset, limit, sort and filters, as in lazy loading in PrimeFaces. A count query is needed too.

Concurrent edits

A user can open a record, leave for lunch and save over somebody's changes. Add a version field:

java
@Entity
public class Customer {
    @Id @GeneratedValue Long id;
    @Version long version;
    String name;
}

On merge, Hibernate compares versions and throws OptimisticLockException when the row changed. Catch it as above. The stale object exception in other contexts is in locking failures. The version must travel with the entity in the view scoped bean, so a hidden field is not needed as long as the object persists between requests.

Validation

Bean Validation annotations on the entity run at the JSF validation phase for bound inputs and again at persist time. Messages appear next to the fields, see validation and converters.

The getter that queries the database

JSF calls a bean's getters several times per request, in different phases and for each component that references the value. A getter that runs a query is therefore a query repeated, and the page that used to be fast gets slow as components are added:

java
// Called on every EL evaluation: five components, five queries
public List<Order> getOrders() {
    return service.findOpenOrders();
}

Load once, in a place that runs once per view, and let the getter return a field:

java
@Named
@ViewScoped
public class OrdersBean implements Serializable {

    @Inject OrderService service;
    private List<Order> orders;

    @PostConstruct
    void init() {
        orders = service.findOpenOrders();
    }

    public List<Order> getOrders() {
        return orders;
    }
}

Count the queries to confirm: with hibernate.generate_statistics=true, log the statement count at the end of the request, and the number should be the same regardless of how many components display the list. A view-scoped bean keeps the list for the life of the view, so decide how it is refreshed after a change, normally by reloading in the action method.

Refresh after a write

A list that was loaded in @PostConstruct is stale after the user saves a row. The action should reload, and it should do so after the transaction has committed, so the service call returns before the bean reads again:

java
public String save() {
    service.update(selected);
    orders = service.findOpenOrders();
    return null;
}

Returning null re-renders the same view. Returning an outcome string redirects, and a view-scoped bean is discarded by navigation to another view, so the reload only matters when staying on the page.

Where transactions begin and end

Keep the transaction inside the service method. A request-wide transaction, opened by a filter and closed after rendering, holds a database connection while the page is built and while the browser downloads it. With a pool of 20 connections, 20 slow clients can stall the whole application. A service method that opens, works and commits within milliseconds holds a connection only for as long as the work takes.

PatternConnection held forRisk
Transaction per service methodThe methodLazy loading outside the method fails
Transaction per requestThe whole requestPool exhaustion under slow clients
Transaction per conversationSeveral requests, often minutesLong locks, stale data
No transaction for readsThe queryFine for single queries

The first row is the one to choose, and its cost is the lazy loading problem covered above: load what the page needs inside the service, with a fetch join or a DTO.

Testing the service without JSF

A thin bean means the logic lives in a class that can be exercised by a test without a faces context. A test with a real database, through Testcontainers or an in-memory one that matches the production dialect, covers the transaction boundaries:

java
@Test
void updateRollsBackOnFailure() {
    Order order = service.create("A-1");
    assertThrows(OptimisticLockException.class, () -> service.updateStale(order.getId(), 0L));
    assertEquals("NEW", service.find(order.getId()).getStatus());
}

The test shows that a failed update leaves the row unchanged. A bean-level test of the same behaviour needs a servlet container and takes ten times as long, so the split pays for itself in feedback speed as well as design.

Signs the layering has slipped

If a bean imports EntityManager, a service method returns an entity that the page then walks into lazy collections, or a @Transactional appears on a bean, the boundary is leaking. Each of these is cheap to fix when found early and expensive when a screen depends on it.

Monitoring the page's database cost

A page's database use is easy to measure and rarely measured. Log the statement count and total database time per request in a filter, using Hibernate statistics or a datasource proxy, and chart the highest values per page. A page that moves from 5 to 60 statements after a release shows up the same day.

Set a budget for the main screens, such as ten statements, and fail a test when a change exceeds it. The budget turns performance into something that is reviewed like any other requirement.

Where this does not apply

With Spring Boot instead of CDI, the same shape applies using Spring services, see JSF with Spring Boot. References: Jakarta Persistence and the Hibernate documentation.

Also inHibernate
Taggedhow to
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.