我想知道我使用 OpenJpa 2 保存实体的方式是否正确。
我从我反序列化的休息服务接收对象,然后保存此实例:
- 开始交易
- 从数据库中检索实例(即使我已经有了这个实例)
- 将分离实例的属性复制到从数据库检索到的实例
- 调用合并
- 提交交易
如果是带有compsitions的复杂实体模型,那就太痛苦了!
public boolean save(Collection<Event> events) throws DataException {
if (events == null) {
throw new DataException("Cannot save null events");
}
EntityManager em = getEntityManager();
try {
em.getTransaction().begin();
for (Event event : events) {
boolean add = true;
if(event.getKey() > 0){
Event previousEvent = em.find(Event.class, event.getKey());
if (previousEvent != null) {
//update
previousEvent.setTitle(event.getTitle());
previousEvent.setDate(event.getDate());
previousEvent.setDescription(event.getDescription());
List<Member> participants = new ArrayList<>();
for(Member m : event.getParticipants()){
Member participant = em.find(Member.class, m.getKey());
if(participant != null){
participants.add(participant);
}
}
previousEvent.setParticipants(participants);
List<Member> registrants = new ArrayList<>();
for(Member m : event.getRegistrants()){
Member registrant = em.find(Member.class, m.getKey());
if(registrant != null){
participants.add(registrant);
}
}
previousEvent.setRegistrants(registrants);
em.merge(previousEvent);
add = false;
}
}
if(add) {
//add
em.persist(event);
}
}
em.getTransaction().commit();
} catch (PersistenceException pe) {
pe.printStackTrace();
throw new DataException("An error occured while saving the event", pe);
} finally {
em.close();
}
return true;
}
有什么建议吗?
谢谢