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.fracturedatlas.athena.apa.impl.jpa.JpaApaAdapter.java

private TicketProp saveTicketProp(TicketProp prop) throws InvalidValueException {
    EntityManager em = this.emf.createEntityManager();
    try {/* w  w w.  j ava  2  s . co  m*/
        em.getTransaction().begin();
        enforceStrict(prop.getPropField(), prop.getValueAsString());
        enforceCorrectValueType(prop.getPropField(), prop, em);
        prop.setId(LongUserType.massageToLong(prop.getId()));
        prop = (TicketProp) em.merge(prop);
        em.getTransaction().commit();
        return prop;
    } finally {
        cleanup(em);
    }
}

From source file:op.care.dfn.PnlDFN.java

private java.util.List<Component> addCommands() {

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

    /***//  w w  w.  j  a v a 2s .  c  o  m
     *      _     _            _       _     _
     *     | |__ | |_ _ __    / \   __| | __| |
     *     | '_ \| __| '_ \  / _ \ / _` |/ _` |
     *     | |_) | |_| | | |/ ___ \ (_| | (_| |
     *     |_.__/ \__|_| |_/_/   \_\__,_|\__,_|
     *
     */
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {

        final JideButton btnAdd = GUITools.createHyperlinkButton(SYSTools.xx("nursingrecords.dfn.btnadd"),
                SYSConst.icon22add, null);
        btnAdd.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                if (!resident.isActive()) {
                    OPDE.getDisplayManager()
                            .addSubMessage(new DisplayMessage("misc.msg.cantChangeInactiveResident"));
                    return;
                }

                final JidePopup popup = new JidePopup();
                popup.setMovable(false);
                PnlSelectIntervention pnl = new PnlSelectIntervention(new Closure() {
                    @Override
                    public void execute(Object o) {
                        popup.hidePopup();
                        if (o != null) {
                            Object[] objects = (Object[]) o;
                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();
                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);

                                for (Object obj : objects) {
                                    Intervention intervention = em.merge((Intervention) obj);
                                    DFN dfn = em.merge(new DFN(resident, intervention));

                                    // Set Target and Actual according to the setting of JDCDate
                                    DateTime now = new DateTime();
                                    DateMidnight onDemandPIT = new DateMidnight(jdcDate.getDate());
                                    DateTime newDateTime = onDemandPIT.toDateTime()
                                            .plusHours(now.getHourOfDay()).plusMinutes(now.getMinuteOfHour())
                                            .plusSeconds(now.getSecondOfMinute());
                                    dfn.setSoll(newDateTime.toDate());
                                    dfn.setIst(newDateTime.toDate());

                                    CollapsiblePane cp1 = createCP4(dfn);
                                    synchronized (mapDFN2Pane) {
                                        mapDFN2Pane.put(dfn, cp1);
                                    }
                                    synchronized (mapShift2DFN) {
                                        mapShift2DFN.get(dfn.getShift()).add(dfn);
                                    }
                                }

                                em.getTransaction().commit();

                                CollapsiblePane cp2 = createCP4(DFNTools.SHIFT_ON_DEMAND);
                                synchronized (mapShift2Pane) {
                                    mapShift2Pane.put(DFNTools.SHIFT_ON_DEMAND, cp2);
                                }
                                buildPanel(false);
                                try {
                                    synchronized (mapShift2Pane) {
                                        mapShift2Pane.get(DFNTools.SHIFT_ON_DEMAND).setCollapsed(false);
                                    }
                                } catch (PropertyVetoException e) {
                                    OPDE.debug(e);
                                }

                            } 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();
                            }
                        }
                    }
                });
                popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
                popup.getContentPane().add(pnl);
                popup.setOwner(btnAdd);
                popup.removeExcludedComponent(pnl);
                popup.setDefaultFocusComponent(pnl);
                GUITools.showPopup(popup, SwingConstants.NORTH);
            }
        });
        list.add(btnAdd);

    }

    final JideButton printPrescription = GUITools.createHyperlinkButton("nursingrecords.dfn.print",
            SYSConst.icon22print2, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent actionEvent) {

                    String html = "";

                    synchronized (mapShift2DFN) {
                        html += "<h1 id=\"fonth1\" >" + ResidentTools.getFullName(resident) + "</h1>";
                        html += SYSConst.html_h2(SYSTools.xx("nursingrecords.bhp") + ": "
                                + SYSConst.html_bold(DateFormat.getDateInstance().format(jdcDate.getDate())));

                        for (Byte shift : new Byte[] { DFNTools.SHIFT_ON_DEMAND, DFNTools.SHIFT_VERY_EARLY,
                                DFNTools.SHIFT_EARLY, DFNTools.SHIFT_LATE, DFNTools.SHIFT_VERY_LATE }) {
                            html += DFNTools.getDFNsAsHTMLtable(mapShift2DFN.get(shift));
                        }
                    }

                    SYSFilesTools.print(html, true);
                }
            });
    list.add(printPrescription);
    return list;
}

From source file:org.rhq.enterprise.server.alert.AlertDefinitionWithComplexNotificationsTest.java

private void removeNoExceptions(final Object o) {
    try {//  w  w  w .  j  a  v  a 2 s. c o m
        executeInTransaction(false, new TransactionCallback() {
            public void execute() {
                EntityManager em = getEntityManager();
                Object o2 = em.merge(o);

                if (o2 instanceof Resource) {
                    ResourceTreeHelper.deleteResource(em, (Resource) o2);
                } else {
                    em.remove(o2);
                }

                em.flush();
            }
        });
    } catch (Exception e) {
        LOG.error("Failed to DELETE an object from database: " + o, e);
    }
}

From source file:org.eclipse.smila.connectivity.deltaindexing.jpa.impl.DeltaIndexingManagerImpl.java

/**
 * Creates or updates an entry in the delta indexing database and sets the visited flag.
 * /*  w w  w . j a v a  2  s  .co m*/
 * @param em
 *          the EntityManager
 * @param dao
 *          the DeltaIndexingDao if a former entry exists or null
 * @param id
 *          the id of the record (just for logging)
 * @param hash
 *          the delta indexing hash
 * @param isCompound
 *          boolean flag if the record identified by id is a compound record (true) or not (false)
 * @throws DeltaIndexingException
 *           if any error occurs
 */
private void visitNewOrChangedDao(final EntityManager em, DeltaIndexingDao dao, final ConnectivityId id,
        final String hash, final boolean isCompound) throws DeltaIndexingException {
    final EntityTransaction transaction = em.getTransaction();
    try {
        transaction.begin();
        if (dao == null) {
            dao = new DeltaIndexingDao(id, hash, isCompound, true);
            em.persist(dao);
            if (_log.isTraceEnabled()) {
                _log.trace("created and visited id: " + id);
            }
        } else {
            dao.modifyAndVisit(hash);
            em.merge(dao);
            if (_log.isTraceEnabled()) {
                _log.trace("visited Id:" + id);
            }
        }
        transaction.commit();
    } catch (final Exception e) {
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new DeltaIndexingException("error visiting id: " + id, e);
    }
}

From source file:org.sigmah.server.endpoint.export.sigmah.handler.OrgUnitModelHandler.java

/**
 * Save the category element of a question choice element.
 * /* w  w w. ja  va 2s.  c  om*/
 * @param categoryElement
 *            the category element to save.
 * @param em
 *            the entity manager.
 */
private void saveOrgUnitModelCategoryElement(CategoryElement categoryElement, EntityManager em) {
    if (!modelesImport.contains(categoryElement)) {
        modelesImport.add(categoryElement);

        if (!modelesReset.containsKey(categoryElement)) {
            CategoryElement key = categoryElement;
            categoryElement.setId(null);

            CategoryType parentType = categoryElement.getParentType();
            if (!modelesImport.contains(parentType)) {
                modelesImport.add(parentType);

                if (!modelesReset.containsKey(parentType)) {
                    CategoryType parentKey = parentType;
                    parentType.setId(null);

                    List<CategoryElement> elements = parentType.getElements();
                    if (elements != null) {
                        parentType.setElements(null);
                        em.persist(parentType);
                        for (CategoryElement element : elements) {
                            categoryElement.setParentType(parentType);
                            saveOrgUnitModelCategoryElement(element, em);
                        }
                        parentType.setElements(elements);
                        em.merge(parentType);
                    } else {
                        em.persist(parentType);
                    }
                    modelesReset.put(parentKey, parentType);
                } else {
                    parentType = (CategoryType) modelesReset.get(parentType);
                }
            }
            categoryElement.setParentType(parentType);
            em.persist(categoryElement);
            modelesReset.put(key, categoryElement);
        } else {
            categoryElement = (CategoryElement) modelesReset.get(categoryElement);
        }
    }
}

From source file:org.apache.juddi.api.impl.JUDDIApiImpl.java

/**
 * Saves nodes(s) to the persistence layer. This method is specific to
 * jUDDI. Administrative privilege required. This is used for server to server subscriptions and for future use
 * with replication. Administrative privilege required.
 * @param body/*from   w w  w  .  ja v  a  2 s .  c o  m*/
 * @return NodeDetail
 * @throws DispositionReportFaultMessage 
 */
public NodeDetail saveNode(SaveNode body) throws DispositionReportFaultMessage {

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidateNode(publisher).validateSaveNode(em, body);

        NodeDetail result = new NodeDetail();

        List<org.apache.juddi.api_v3.Node> apiNodeList = body.getNode();
        ;
        for (org.apache.juddi.api_v3.Node apiNode : apiNodeList) {

            org.apache.juddi.model.Node modelNode = new org.apache.juddi.model.Node();

            MappingApiToModel.mapNode(apiNode, modelNode);

            Object existingUddiEntity = em.find(modelNode.getClass(), modelNode.getName());
            if (existingUddiEntity != null) {
                em.merge(modelNode);
            } else {
                em.persist(modelNode);
            }

            result.getNode().add(apiNode);
        }

        tx.commit();
        return result;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

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

private List<TicketProp> saveTicketProps(List<TicketProp> props) {
    List<TicketProp> outProps = new ArrayList<TicketProp>();
    EntityManager em = this.emf.createEntityManager();
    try {/*from w w w . j av  a 2s  . c o  m*/
        em.getTransaction().begin();

        for (TicketProp prop : props) {
            enforceStrict(prop.getPropField(), prop.getValueAsString());
            enforceCorrectValueType(prop.getPropField(), prop, em);
            prop.setId(LongUserType.massageToLong(prop.getId()));
            prop = (TicketProp) em.merge(prop);
        }
        em.getTransaction().commit();
        return outProps;
    } catch (ApaException e) {

        em.getTransaction().rollback();
        throw e;
    } finally {
        cleanup(em);
    }

}

From source file:org.apache.juddi.api.impl.JUDDIApiImpl.java

/**
 * Saves clerk(s) to the persistence layer. This method is specific to
 * jUDDI. This is used for server to server subscriptions and for future use
 * with replication. Administrative privilege required.
 * @param body//from w w w. ja va2 s  .  co  m
 * @return ClerkDetail
 * @throws DispositionReportFaultMessage 
 */
public ClerkDetail saveClerk(SaveClerk body) throws DispositionReportFaultMessage {

    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = em.getTransaction();
    try {
        tx.begin();

        UddiEntityPublisher publisher = this.getEntityPublisher(em, body.getAuthInfo());

        new ValidateClerk(publisher).validateSaveClerk(em, body);

        ClerkDetail result = new ClerkDetail();

        List<org.apache.juddi.api_v3.Clerk> apiClerkList = body.getClerk();
        ;
        for (org.apache.juddi.api_v3.Clerk apiClerk : apiClerkList) {

            org.apache.juddi.model.Clerk modelClerk = new org.apache.juddi.model.Clerk();

            MappingApiToModel.mapClerk(apiClerk, modelClerk);

            Object existingUddiEntity = em.find(modelClerk.getClass(), modelClerk.getClerkName());
            if (existingUddiEntity != null) {
                em.merge(modelClerk);
            } else {
                em.persist(modelClerk);
            }

            result.getClerk().add(apiClerk);
        }

        tx.commit();
        return result;
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        em.close();
    }
}

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

@Override
public void deletePropValue(Object propFieldId, Object propValueId) {
    EntityManager em = this.emf.createEntityManager();
    try {/*from   w w w.  j  a va 2  s  .  c o  m*/
        Long longId = LongUserType.massageToLong(propValueId);
        PropValue pv = em.find(PropValue.class, longId);
        if (pv != null) {
            PropField propField = getPropField(pv.getPropField().getId());
            propField.getPropValues().remove(pv);
            em.getTransaction().begin();
            em.remove(pv);
            propField = em.merge(propField);
            em.getTransaction().commit();
        }
    } finally {
        cleanup(em);
    }
}

From source file:com.gnadenheimer.mg.frames.admin.FrameConfigAdmin.java

private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    try {//from  w  ww .jav  a  2  s .c  o  m
        CurrentUser currentUser = CurrentUser.getInstance();
        Map<String, String> persistenceMap = Utils.getInstance().getPersistenceMap();
        EntityManager entityManager = Persistence.createEntityManagerFactory("mg_PU", persistenceMap)
                .createEntityManager();
        entityManager.getTransaction().begin();

        List<TblEntidades> list = (List<TblEntidades>) entityManager.createQuery("select e from TblEntidades e")
                .getResultList();

        for (TblEntidades e : list) {
            String nombreviejo = e.getNombres();
            if (nombreviejo.contains(",")) {
                String[] parts = nombreviejo.split(",");
                e.setNombres(parts[0].trim());
                e.setApellidos(parts[1].trim());
                entityManager.merge(e);
            }
        }

        entityManager.getTransaction().commit();
        entityManager.getTransaction().begin();
        JOptionPane.showMessageDialog(null, "Nombres actualizados!");
    } catch (Exception ex) {
        JOptionPane.showMessageDialog(null,
                Thread.currentThread().getStackTrace()[1].getMethodName() + " - " + ex.getMessage());
        LOGGER.error(Thread.currentThread().getStackTrace()[1].getMethodName(), ex);
    }
}