Example usage for javax.persistence EntityManager merge

List of usage examples for javax.persistence EntityManager merge

Introduction

In this page you can find the example usage for javax.persistence EntityManager merge.

Prototype

public <T> T merge(T entity);

Source Link

Document

Merge the state of the given entity into the current persistence context.

Usage

From source file:org.opencastproject.capture.admin.impl.CaptureAgentStateServiceImpl.java

/**
 * Updates or adds an agent to the database.
 * // w  ww.  j  a  v a2s  . co  m
 * @param agent
 *          The Agent you wish to modify or add in the database.
 */
protected void updateAgentInDatabase(AgentImpl agent) {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        AgentImpl existing = getAgentEntity(agent.getName(), agent.getOrganization(), em);
        if (existing == null) {
            em.persist(agent);
        } else {
            existing.setConfiguration(agent.getConfiguration());
            existing.setLastHeardFrom(agent.getLastHeardFrom());
            existing.setState(agent.getState());
            existing.setSchedulerRoles(agent.getSchedulerRoles());
            existing.setUrl(agent.getUrl());
            em.merge(existing);
        }
        tx.commit();
        agentCache.put(agent.getName().concat(DELIMITER).concat(agent.getOrganization()),
                Tuple.tuple(agent.getState(), agent.getConfiguration()));
    } catch (RollbackException e) {
        logger.warn("Unable to commit to DB in updateAgent.");
        throw e;
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:de.zib.gndms.logic.model.TaskAction.java

/**
 * Initializes a TaskAction by denoting an EntityManager and a model.
 *
 * The model is made persistent by the EntityManager.
 * The EntityManager and the model are stored, using {@code setOwnEntityManager()} and {@code setModelAndBackup()}.
 * A Backup of the model is done./*from  w  w  w. j a v  a  2  s . co  m*/
 *
 *
 * @param em an EntityManager, storing AbstractTasks
 * @param model an AbstractTask to be stored as model of {@code this} and to be stored in the database
 */
public void initFromModel(final EntityManager em, AbstractTask model) {

    boolean wasActive = em.getTransaction().isActive();
    if (!wasActive)
        em.getTransaction().begin();
    try {
        final boolean contained = em.contains(model);
        if (!contained) {
            try {
                em.persist(model);
            } catch (EntityExistsException e) {
                model = em.merge(model);
            }
        }
        if (!wasActive)
            em.getTransaction().commit();
        setOwnEntityManager(em);
        setModelAndBackup(model);
    } finally {
        if (em.getTransaction().isActive())
            em.getTransaction().rollback();
    }
}

From source file:org.apache.oozie.service.JPAService.java

/**
 * Execute multiple update/insert queries in one transaction
 * @param insertBeans list of beans to be inserted
 * @param updateQueryList list of update queries
 * @param deleteBeans list of beans to be deleted
 * @param em Entity Manager//from w w w.ja va 2s.  c  om
 * @throws JPAExecutorException
 */
public void executeBatchInsertUpdateDelete(Collection<JsonBean> insertBeans, List<QueryEntry> updateQueryList,
        Collection<JsonBean> deleteBeans, EntityManager em) throws JPAExecutorException {
    Instrumentation.Cron cron = new Instrumentation.Cron();
    try {

        LOG.trace("Executing Queries in Batch");
        cron.start();
        em.getTransaction().begin();
        if (updateQueryList != null && updateQueryList.size() > 0) {
            for (QueryEntry q : updateQueryList) {
                if (instr != null) {
                    instr.incr(INSTRUMENTATION_GROUP_JPA, q.getQueryName().name(), 1);
                }
                q.getQuery().executeUpdate();
            }
        }
        if (insertBeans != null && insertBeans.size() > 0) {
            for (JsonBean bean : insertBeans) {
                em.persist(bean);
            }
        }
        if (deleteBeans != null && deleteBeans.size() > 0) {
            for (JsonBean bean : deleteBeans) {
                em.remove(em.merge(bean));
            }
        }
        if (em.getTransaction().isActive()) {
            if (FaultInjection.isActive("org.apache.oozie.command.SkipCommitFaultInjection")) {
                throw new RuntimeException("Skipping Commit for Failover Testing");
            }
            em.getTransaction().commit();
        }
    } catch (PersistenceException e) {
        throw new JPAExecutorException(ErrorCode.E0603, e);
    } finally {
        processFinally(em, cron, "batchqueryexecutor", true);
    }
}

From source file:op.care.values.PnlValues.java

private void addValue(final ResValueTypes vtype) {

    final String keyType = vtype.getID() + ".xtypes";

    new DlgValue(new ResValue(resident, vtype), DlgValue.MODE_NEW, new Closure() {
        @Override/*from w  w w. ja  va2  s  . com*/
        public void execute(Object o) {
            ResValue myValue = null;

            if (o != null) {

                EntityManager em = OPDE.createEM();
                try {
                    em.getTransaction().begin();
                    myValue = em.merge((ResValue) o);
                    em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                    em.getTransaction().commit();

                } catch (OptimisticLockException ole) {
                    OPDE.warn(ole);
                    if (em.getTransaction().isActive()) {
                        em.getTransaction().rollback();
                    }
                    if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                        OPDE.getMainframe().emptyFrame();
                        OPDE.getMainframe().afterLogin();
                    }
                    OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                } catch (Exception e) {
                    if (em.getTransaction().isActive()) {
                        em.getTransaction().rollback();
                    }
                    OPDE.fatal(e);
                } finally {
                    em.close();
                }

                if (myValue != null) {

                    DateTime dt = new DateTime(myValue.getPit());

                    //                        final String keyDay = vtype.getID() + ".xtypes." + dt.toLocalDate() + ".day";
                    final String keyYear = vtype.getID() + ".xtypes." + Integer.toString(dt.getYear())
                            + ".year";
                    //                        final LocalDate week = SYSCalendar.max(SYSCalendar.bow(dt.toLocalDate()), new LocalDate(dt.getYear(), 1, 1));
                    //                        final String keyWeek = vtype.getID() + ".xtypes." + week + ".week";

                    synchronized (mapType2Values) {

                        if (!mapType2Values.containsKey(keyYear)) {
                            mapType2Values.put(keyYear,
                                    ResValueTools.getResValues(resident, vtype, dt.getYear()));
                        }

                        if (!mapType2Values.get(keyYear).contains(myValue)) {
                            mapType2Values.get(keyYear).add(myValue);
                            Collections.sort(mapType2Values.get(keyYear));
                        }
                        //                            }
                    }

                    try {
                        // eh ?
                        synchronized (cpMap) {
                            cpMap.get(keyType).setCollapsible(true);

                            if (cpMap.get(keyType).isCollapsed()) {
                                cpMap.get(keyType).setCollapsed(false);
                            }
                            if (cpMap.containsKey(keyYear) && cpMap.get(keyYear).isCollapsed()) {
                                cpMap.get(keyYear).setCollapsed(false);
                            }

                        }
                    } catch (PropertyVetoException e) {
                        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                    }

                    createCP4Type(vtype);

                    buildPanel();

                    final ResValue myValueCopy = myValue;
                    synchronized (linemap) {
                        GUITools.scroll2show(jspValues, linemap.get(myValueCopy), cpsValues, new Closure() {
                            @Override
                            public void execute(Object o) {
                                GUITools.flashBackground(linemap.get(myValueCopy), Color.YELLOW, 2);
                            }
                        });
                    }

                }
            }

        }
    });
}

From source file:fr.mby.opa.picsimpl.dao.DbProposalDao.java

@Override
public ProposalBag createBag(final ProposalBag bag, final long branchId) {
    Assert.notNull(bag, "No ProposalBag supplied !");
    Assert.isNull(bag.getId(), "Id should not be set for creation !");

    new TxCallback(this.getEmf()) {

        @Override//from  ww  w  . jav  a  2s .c  o  m
        // @SuppressWarnings("unchecked")
        protected void executeInTransaction(final EntityManager em) {
            // Retrieve branch
            final ProposalBranch branch = em.find(ProposalBranch.class, branchId,
                    LockModeType.PESSIMISTIC_WRITE);
            if (branch == null) {
                throw new ProposalBranchNotFoundException();
            }

            // Retrieve base bag (parent bag) and lock the row
            // final Query findParentQuery = em.createNamedQuery(ProposalBag.FIND_LAST_BRANCH_BAG);
            // findParentQuery.setParameter("branchId", branchId);
            // findParentQuery.setLockMode(LockModeType.PESSIMISTIC_WRITE);

            // Persist bag with its parent
            // final ProposalBag parentBag = Iterables.getFirst(findParentQuery.getResultList(), null);
            // bag.setBaseProposal(parentBag);
            // em.persist(bag);

            // Persist bag with its parent
            bag.setBaseProposal(branch.getHead());
            em.persist(bag);

            // Update branch head pointer
            branch.setHead(bag);
            em.merge(branch);
        }
    };

    return bag;
}

From source file:op.care.values.PnlValues.java

private java.util.List<Component> addCommands() {
    java.util.List<Component> list = new ArrayList<Component>();

    JideButton controlButton = GUITools.createHyperlinkButton(
            SYSTools.xx("nursingrecords.vitalparameters.btnControlling.tooltip"), SYSConst.icon22magnify1,
            new ActionListener() {
                @Override// w ww  .  j  a va2  s .c om
                public void actionPerformed(ActionEvent actionEvent) {
                    if (!resident.isActive()) {
                        OPDE.getDisplayManager()
                                .addSubMessage(new DisplayMessage("misc.msg.cantChangeInactiveResident"));
                        return;
                    }
                    new DlgValueControl(resident, new Closure() {
                        @Override
                        public void execute(Object o) {
                            if (o != null) {
                                EntityManager em = OPDE.createEM();
                                try {
                                    em.getTransaction().begin();
                                    Resident myResident = em.merge(resident);
                                    em.lock(myResident, LockModeType.OPTIMISTIC);
                                    myResident.setControlling((Properties) o);
                                    em.getTransaction().commit();

                                    resident = myResident;
                                } catch (OptimisticLockException ole) {
                                    OPDE.warn(ole);
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                        OPDE.getMainframe().emptyFrame();
                                        OPDE.getMainframe().afterLogin();
                                    }
                                    OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                                } catch (Exception e) {
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    OPDE.fatal(e);
                                } finally {
                                    em.close();
                                }

                            }
                        }
                    });
                }
            });
    list.add(controlButton);

    return list;
}

From source file:cn.buk.hotel.dao.HotelDaoImpl.java

@Override
@Transactional//from   w  w  w.  ja v a2 s .  c o m
public int updateHotelInfo(HotelInfo hotelInfo) {
    int retCode = 0;
    EntityManager em = getEm();
    try {
        if (hotelInfo.getGuestRooms() != null && hotelInfo.getGuestRooms().size() > 0) {
            //?guestrooms, ??
            int count = getEm().createQuery("delete from HotelGuestRoom r where r.hotelInfo = :hotelInfo")
                    .setParameter("hotelInfo", hotelInfo).executeUpdate();
            logger.debug("delete " + count + " guest rooms from hotel --- " + hotelInfo.getHotelCode());
        }
        em.merge(hotelInfo);
        retCode = 1;
    } catch (Exception ex) {
        retCode = -1;
        logger.error("updateHotelInfo failed: (HotelCode: " + hotelInfo.getHotelCode() + ", HotelName: "
                + hotelInfo.getHotelName() + ")" + ex.getMessage());
    }
    return retCode;
}

From source file:org.traccar.web.server.model.DataServiceImpl.java

@Override
public User updateUser(User user) {
    User currentUser = getSessionUser();
    if (user.getLogin().isEmpty() || user.getPassword().isEmpty()) {
        throw new IllegalArgumentException();
    }//from w  ww  .  j a  va2  s . com
    if (currentUser.getAdmin() || (currentUser.getId() == user.getId() && !user.getAdmin())) {
        EntityManager entityManager = getSessionEntityManager();
        synchronized (entityManager) {
            entityManager.getTransaction().begin();
            try {
                // TODO: better solution?
                if (currentUser.getId() == user.getId()) {
                    currentUser.setLogin(user.getLogin());
                    currentUser.setPassword(user.getPassword());
                    currentUser.setUserSettings(user.getUserSettings());
                    currentUser.setAdmin(user.getAdmin());
                    entityManager.merge(currentUser);
                    user = currentUser;
                } else {
                    // TODO: handle other users
                }

                entityManager.getTransaction().commit();
                setSessionUser(user);
                return user;
            } catch (RuntimeException e) {
                entityManager.getTransaction().rollback();
                throw e;
            }
        }
    } else {
        throw new SecurityException();
    }
}

From source file:org.fracturedatlas.athena.apa.impl.jpa.JpaApaAdapter.java

public void deleteTicketProp(TicketProp prop, EntityManager em) {
    boolean useTransaction = (em == null);
    if (em == null) {
        em = this.emf.createEntityManager();
    }//w  w  w  .  ja v  a2  s .  c  o m
    try {
        if (useTransaction) {
            em.getTransaction().begin();
        }
        prop = em.merge(prop);

        if (prop == null) {
            throw new ApaException("Cannot delete prop.  Prop was not found.");
        }

        JpaRecord t = prop.getTicket();

        if (t == null) {
            throw new ApaException("Cannot delete prop.  This prop has not been assigned to a ticket.");
        }
        t.getTicketProps().remove(prop);
        em.remove(prop);
        t = em.merge(t);
        if (useTransaction) {
            em.getTransaction().commit();
        }
    } finally {
        if (useTransaction) {
            cleanup(em);
        }
    }
}

From source file:op.allowance.PnlAllowance.java

private PnlTX getPnlTX(Resident resident, final Allowance allowance) {
    final BigDecimal editAmount = allowance != null ? allowance.getAmount() : null;
    final Allowance allow = (allowance == null ? new Allowance(resident) : allowance);

    return new PnlTX(allow, new Closure() {
        @Override//from   w w  w.  j  a v  a2s.com
        public void execute(Object o) {
            if (o != null) {

                EntityManager em = OPDE.createEM();
                try {
                    em.getTransaction().begin();
                    final Allowance myAllowance = em.merge((Allowance) o);
                    em.lock(em.merge(myAllowance.getResident()), LockModeType.OPTIMISTIC);
                    em.getTransaction().commit();

                    DateTime txDate = new DateTime(myAllowance.getPit());

                    final String keyResident = myAllowance.getResident().getRID();
                    final String keyYear = myAllowance.getResident().getRID() + "-" + txDate.getYear();
                    final String keyMonth = myAllowance.getResident().getRID() + "-" + txDate.getYear() + "-"
                            + txDate.getMonthOfYear();

                    if (!lstResidents.contains(myAllowance.getResident())) {
                        lstResidents.add(myAllowance.getResident());
                        Collections.sort(lstResidents);
                    }

                    if (!cashmap.containsKey(keyMonth)) {
                        cashmap.put(keyMonth,
                                AllowanceTools.getMonth(myAllowance.getResident(), myAllowance.getPit()));
                    } else {

                        if (cashmap.get(keyMonth).contains(myAllowance)) {
                            cashmap.get(keyMonth).remove(myAllowance);
                        }
                        cashmap.get(keyMonth).add(myAllowance);

                        Collections.sort(cashmap.get(keyMonth));
                    }

                    // little trick to fix the carries
                    if (editAmount != null) {
                        updateCarrySums(myAllowance.getResident(), new LocalDate(myAllowance.getPit()),
                                editAmount.negate());
                    }
                    // add the new / edited amount
                    updateCarrySums(myAllowance);

                    createCP4(myAllowance.getResident());

                    try {
                        if (cpMap.get(keyResident).isCollapsed())
                            cpMap.get(keyResident).setCollapsed(false);
                        if (cpMap.get(keyYear).isCollapsed())
                            cpMap.get(keyYear).setCollapsed(false);
                        if (cpMap.get(keyMonth).isCollapsed())
                            cpMap.get(keyMonth).setCollapsed(false);
                    } catch (PropertyVetoException e) {
                        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                    }

                    buildPanel();

                    GUITools.scroll2show(jspCash, cpMap.get(keyMonth), cpsCash, new Closure() {
                        @Override
                        public void execute(Object o) {
                            GUITools.flashBackground(linemap.get(myAllowance), Color.YELLOW, 2);
                        }
                    });

                } catch (OptimisticLockException ole) {
                    OPDE.warn(ole);
                    if (em.getTransaction().isActive()) {
                        em.getTransaction().rollback();
                    }
                    if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                        OPDE.getMainframe().emptyFrame();
                        OPDE.getMainframe().afterLogin();
                    }
                    OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                } catch (Exception e) {
                    if (em.getTransaction().isActive()) {
                        em.getTransaction().rollback();
                    }
                    OPDE.fatal(e);
                } finally {
                    em.close();
                }

            }
        }
    });
}