Module jakarta.data.stateful


module jakarta.data.stateful

API for Stateful Repositories in Jakarta Data

A stateful repository is an interface annotated @Repository that defines at least one stateful lifecycle method. A stateful lifecycle method is annotated with exactly one of the following annotations defined in the jakarta.data.repository.stateful package:

Stateful repository interfaces can optionally inherit from the built-in DataRepository interface to define a primary entity class and the type of its Id attribute. Otherwise, if all lifecycle methods specify the same entity class, then the primary entity class is that class.

A stateful repository must not define or inherit any method annotated @Delete, @Insert, @Save, or @Update, which are to be used only on stateless repositories.

Transactions

To ensure a boundary at which updates are persisted to the data store, the application should arrange to have lifecycle methods that cause updates, such as those annotated @Merge, @Persist, and @Remove, as well as other updates made directly to entities, participate in a transaction, the duration of which the same persistence context applies. In Jakarta EE environments where resources are capable of enlistment, a Jakarta Transactions (JTA) transaction can be used.

Examples

The entity and static metamodel for the following code examples are shown in the Attribute Javadoc.

A stateful repository interface:


 @Repository
 public interface Vehicles extends DataRepository<Car, String> {
     @Persist
     @Transactional
     void persist(Car... cars);

     @Refresh
     void refresh(Car car);

     @Remove
     void remove(List<Car> cars);

     @Find
     List<Car> search(Restriction<Car> filter);
 }

Application code relying on the jakarta.transaction.Transactional annotation on the example persist method for container-provided transaction management:


     @Inject
     Vehicles vehicles;

     ...

     vehicles.persist(car1, car2, car3);
 

Application code explicitly managing a transaction covering multiple repository operations and updates to entities:


     @Resource
     UserTransaction tx;

     @Inject
     Vehicles vehicles;

     ...

     tx.begin();
     try {
         for (Car car : vehicles.search(_Car.price.lessThan(5000))) {
             if (car.price > 1000)
                 car.price -= 200;
             else
                 scrapList.add(car);
         }
         if (!scrapList.isEmpty)
             vehicles.remove(scrapList);
     } finally {
         if (tx.getStatus() == Status.STATUS_MARKED_ROLLBACK)
             tx.rollback();
         else
             tx.commit();
     }
 

The Javadoc of the Jakarta Data module provides an overview of Jakarta Data.

Since:
1.1