Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Swapped the order of the @PersistenceContext and @Inject examples because the latter appears to be broken

...

Depending on whether more than one persistence unit has been defined, the way to inject EntityManager varies slightly. Let’s start with a simple scenario, where only a single persistence unit is defined. In this case, an EntityManager can be injected using the @Inject @PersistenceContext annotation.

Code Block
languagejava
titleCreateAddress.java
public class CreateAddress {

   @Inject@PersistenceContext
   private EntityManager entityManager;

   @Property
   private Address address;

   @CommitAfter
   void onSuccess() {
      entityManager.persist(address);
   }
}

Alternatively, you can use the @PersistenceContext @Inject annotation to get the EntityManager injected into a page or component, as shown in the following example.

Code Block
languagejava
titleCreateAddress.java
public class CreateAddress {

   @PersistenceContext@Inject
   private EntityManager entityManager;

   @Property
   private Address address;

   @CommitAfter
   void onSuccess() {
      entityManager.persist(address);
   }
}

If However, if you have multiple instances of persistence-unit defined in the same application, you need to explicitly tell Tapestry which persistence unit you want to get injected. This is what the @PersistenceContext annotation’s name attribute is used for? The following example demonstrates how to inject the persistence unit named DemoUnit.

...