OpenJpa合并分离的对象

时间:2013-01-17 12:42:12

标签: java jpa openjpa

我想知道我用OpenJpa 2保存实体的方式是否正确。

我从我反序列化的休息服务中接收对象,然后保存此实例:

  1. 开始交易
  2. 从数据库中检索实例(即使我已经有了这个实例)
  3. 将分离实例中的属性复制到从DB中检索的实例
  4. 致电合并
  5. 提交交易
  6. 如果复杂的实体模型有竞争,那就太痛苦了!

    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;
    }
    

    有什么建议吗?

    感谢

1 个答案:

答案 0 :(得分:0)

Per Chris'评论 - 您应该只需致电em.merge(event)并让JPA处理所有这些问题。如果需要,它应该自动处理创建一个新的Event行,更新Event属性,以及更新或创建包含的对象。