I have a DAO with @Transactional
annotation and with EntityManager
inside.
Also I have a some IOC managed bean that has one transactional method inside.
And there are 2 entities with uni directional many2one -
@Entity
@Table(name = "AU_EVENT")
public class AuEvent {
@ManyToOne(fetch= FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinColumn(name = "MODULE_ID")
private AuModule auModule;
}
AuModule doesnt have reference on AuEvents
I'm trying to do like this
@Async
@Transactional(propagation = Propagation.REQUIRED)
public void onEvent(String moduleName, String instanceName){
AuModule auModule = auModuleDao.findModule(moduleName, instanceName);
if (auModule == null) {
auModule = new AuModule();
auModule.setInstance(instanceName);
auModule.setName(moduleName);
}
//doesnt help
//auModule = auModuleDao.getEntityManager().merge(auModule);
AuEvent auEvent = new AuEvent();
auEvent.setAuModule(auModule);
auEventDao.persist(auEvent); // error here [AuModule detached]
}
As I read in https://stackoverflow.com/questions/14057333/detached-entity-passed-to-persist-error-with-onetomany-relation I tried to do in this way
@Async
@Transactional(propagation = Propagation.REQUIRED)
public void onEvent(String moduleName, String instanceName){
AuEvent auEvent = new AuEvent();
auEventDao.persist(auEvent);
AuModule auModule = auModuleDao.findModule(moduleName, instanceName);
if (auModule == null) {
auModule = new AuModule();
auModule.setInstance(instanceName);
auModule.setName(moduleName);
}
auEvent.setAuModule(auModule);
auEventDao.persist(auEvent); // error here [AuEvent detached]
}
SO, does anyone know how I can avoid this? PS Please don't suggest me to write DAO method like that -
public void saveEvent(AuEvent auEvent, String moduleName, String instanceName){
log.info("saveEvent({}) called...", auEvent);
AuModule auModule = auModuleDao.findModule(moduleName, instanceName);
if (auModule == null) {
auModule = new AuModule();
auModule.setInstance(instanceName);
auModule.setName(moduleName);
}
auEvent.setAuModule(auModule);
persist(auEvent);
}
I exactly want to save event&module not inside of any DAO
Thanks