Uploaded image for project: 'Spring Framework'
  1. Spring Framework
  2. SPR-11923

Shared EntityManager should immediately throw TransactionRequiredException if no transaction in progress

    XMLWordPrintable

    Details

    • Type: Improvement
    • Status: Closed
    • Priority: Minor
    • Resolution: Complete
    • Affects Version/s: 3.2.9, 4.0.5
    • Fix Version/s: 4.0.6, 4.1 RC1
    • Component/s: Data:ORM
    • Labels:
      None
    • Last commented by a User:
      true

      Description

      Section 7.9.1 of the JPA spec states that in a container managed persistence context (that's what you get with LocalContainerEntityManagerFactoryBean), calls to persist(…), merge(…), etc. need to throw a TransactionRequiredException if there's no transaction in progress. However, we currently don't consider this at all which leads to the effect that code like this will not create an exception but also don't persist the entity:

      @Repository
      public class UserDao {
      
          @PersistenceContext
          private EntityManager em;
      
          public void save(User user) {
              em.persist(user);
          }
      }
      

      Additionally calling em.flush() will trigger the exception being thrown by the persistence provider but you might run into this scenario as the code relies on a transaction being started on a layer above. If that's forgotten, you get running (invalid) code, that's not barking at you in any way.

      Of course this can be worked around by e.g. using Spring Data JPA (which has defaulting of transactions on the repository level) but I think we should adhere to the spec here.

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              juergen.hoeller Juergen Hoeller
              Reporter:
              olivergierke Oliver Drotbohm
              Last updater:
              Spring Issues Spring Issues
              Votes:
              0 Vote for this issue
              Watchers:
              4 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved:
                Days since last comment:
                3 years, 18 weeks, 4 days ago