Creating an Object Using EntityListener

I have a client that has a relationship with the customerBudget object. CustomerEntityListener will create a customerBudget object.

I get the following error:

IllegalStateException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST: de.company.entity.Customer-c4775b5b-413b-0567-3612-e0860bca9300 [new,managed]. 

code in onAfterInsert (client object)

  LoadContext<Customer> loadContext = LoadContext.create(Customer.class); loadContext.setId(entity.getId()); Customer customer = dataManager.load(loadContext); CustomerBudget customerBudget = new CustomerBudget(); customerBudget.setCustomer(customer); CommitContext commitContext = new CommitContext(customerBudget); dataManager.commit(commitContext); 

How to create and save Entites in EntityListener?

+6
source share
1 answer

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.

+7
source

All Articles