You can implement the BeforeInsertEntityListener interface and create a new object in the current persistence context through the EntityManager .
The listener might look like this:
@Component("demo_CustomerEntityListener") public class CustomerEntityListener implements BeforeInsertEntityListener<Customer> { @Inject private Metadata metadata; @Inject private Persistence persistence; @Override public void onBeforeInsert(Customer entity) { CustomerBudget customerBudget = metadata.create(CustomerBudget.class); customerBudget.setCustomer(entity); persistence.getEntityManager().persist(customerBudget); } }
The new object will be stored in the database during transactional commit with the client.
The Metadata.create() method is the preferred way to create instances of objects - for objects with integer identifiers, it assigns an identifier from a sequence; it also handles the extension of the object, if necessary.
Entity listeners work in a transaction that saves an object that allows atomic changes to be made in your data - everything will either be saved or canceled along with the entity on which the listener is called.
Unlike EntityManager , DataManager always creates a new transaction. Therefore, you should use it in an entity listener only if you really want to load or save objects in a separate transaction. I'm not sure why you get this particular exception, but your code looks weird: you load the Customer instance that is in the database, instead of using the instance that is passed to the listener. When I tried to run your HSQLDB code, the server went to infinite blocking - a new transaction inside the DataManager waits until the current transaction that saves the client is completed.
source share