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:eu.forgestore.ws.impl.FStoreJpaController.java

public Category updateCategory(Category c) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();/*w ww.  ja v a 2s .  c  o  m*/
    Category resis = entityManager.merge(c);
    entityTransaction.commit();

    return resis;
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public FStoreUser updateFStoreUser(FStoreUser bu) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();//from   w  ww  .  j  a  v a  2s.  co m
    FStoreUser resis = entityManager.merge(bu);
    entityTransaction.commit();

    return resis;
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public Product updateProduct(Product bm) {
    logger.info("================= updateProduct ==================");
    logger.info("bmgetId=" + bm.getId());
    logger.info("bm getName= " + bm.getName());
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();/*w  w  w  . j a v a 2 s  .c om*/
    Product resis = entityManager.merge(bm);
    entityTransaction.commit();

    return resis;
}

From source file:eu.forgestore.ws.impl.FStoreJpaController.java

public FStoreProperty updateProperty(FStoreProperty p) {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();

    entityTransaction.begin();//www  . java  2 s. co  m
    FStoreProperty bp = entityManager.merge(p);
    entityTransaction.commit();

    return bp;
}

From source file:in.bookmylab.jpa.JpaDAO.java

/**
 * @param xrd//  w w w.j a  v  a2s . com
 * @param em
 */
private void fixAnalysisModesAndResourceType(ResourceBooking booking, EntityManager em, boolean isUpdate) {
    // Analysis modes deletion
    if (booking.analysisModes != null) {
        for (Iterator<AnalysisMode> itr = booking.analysisModes.iterator(); itr.hasNext();) {
            AnalysisMode a = itr.next();
            if (a.deleted) {
                if (isUpdate) {
                    em.remove(em.merge(a));
                }
                itr.remove(); // Remove from collection
            } else {
                // Attach resource type
                Query q = em.createNamedQuery("ResourceType.findByCode");
                ResourceType rt = (ResourceType) q
                        .setParameter("code", StringUtils.upperCase(a.resourceType.code)).getSingleResult();
                a.resourceType = rt;
                if (isUpdate) {
                    em.merge(a);
                }
            }
        }
    }
}

From source file:op.care.sysfiles.PnlFiles.java

private void tblFilesMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblFilesMousePressed

    Point p = evt.getPoint();//from  ww w .j a  v  a  2  s. co  m
    ListSelectionModel lsm = tblFiles.getSelectionModel();
    Point p2 = evt.getPoint();
    SwingUtilities.convertPointToScreen(p2, tblFiles);
    final Point screenposition = p2;

    boolean singleRowSelected = lsm.getMaxSelectionIndex() == lsm.getMinSelectionIndex();

    final int row = tblFiles.rowAtPoint(p);
    final int col = tblFiles.columnAtPoint(p);

    if (singleRowSelected) {
        lsm.setSelectionInterval(row, row);
    }

    final TMSYSFiles tm = (TMSYSFiles) tblFiles.getModel();
    final SYSFiles sysfile = tm.getRow(tblFiles.convertRowIndexToModel(row));

    if (SwingUtilities.isRightMouseButton(evt)) {

        SYSTools.unregisterListeners(menu);
        menu = new JPopupMenu();

        // SELECT
        JMenuItem itemPopupShow = new JMenuItem(SYSTools.xx("misc.commands.show"), SYSConst.icon22magnify1);
        itemPopupShow.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SYSFilesTools.handleFile(sysfile, Desktop.Action.OPEN);
            }
        });
        menu.add(itemPopupShow);

        if (col == TMSYSFiles.COL_DESCRIPTION
                && OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {

            final JMenuItem itemPopupEdit = new JMenuItem(SYSTools.xx("misc.commands.edit"),
                    SYSConst.icon22edit3);
            itemPopupEdit.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {

                    final JidePopup popup = new JidePopup();
                    popup.setMovable(false);
                    popup.getContentPane()
                            .setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));

                    final JComponent editor = new JTextArea(sysfile.getBeschreibung(), 10, 40);
                    ((JTextArea) editor).setLineWrap(true);
                    ((JTextArea) editor).setWrapStyleWord(true);
                    ((JTextArea) editor).setEditable(true);

                    popup.getContentPane().add(new JScrollPane(editor));
                    final JButton saveButton = new JButton(SYSConst.icon22apply);
                    saveButton.addActionListener(new ActionListener() {
                        @Override
                        public void actionPerformed(ActionEvent actionEvent) {
                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();
                                popup.hidePopup();
                                SYSFiles mySysfile = em.merge(sysfile);
                                mySysfile.setBeschreibung(((JTextArea) editor).getText().trim());
                                em.getTransaction().commit();
                                tm.setSYSFile(tblFiles.convertRowIndexToModel(row), mySysfile);
                            } catch (Exception e) {
                                em.getTransaction().rollback();
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }

                        }
                    });

                    saveButton.setHorizontalAlignment(SwingConstants.RIGHT);
                    JPanel pnl = new JPanel(new BorderLayout(10, 10));
                    JScrollPane pnlEditor = new JScrollPane(editor);

                    pnl.add(pnlEditor, BorderLayout.CENTER);
                    JPanel buttonPanel = new JPanel();
                    buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.LINE_AXIS));
                    buttonPanel.add(saveButton);
                    pnl.setBorder(new EmptyBorder(10, 10, 10, 10));
                    pnl.add(buttonPanel, BorderLayout.SOUTH);

                    popup.setOwner(tblFiles);
                    popup.removeExcludedComponent(tblFiles);
                    popup.getContentPane().add(pnl);
                    popup.setDefaultFocusComponent(editor);

                    popup.showPopup(screenposition.x, screenposition.y);

                }
            });
            menu.add(itemPopupEdit);
        }

        if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.DELETE, internalClassID)) {
            JMenuItem itemPopupDelete = new JMenuItem(SYSTools.xx("misc.commands.delete"),
                    SYSConst.icon22delete);
            itemPopupDelete.addActionListener(new java.awt.event.ActionListener() {

                public void actionPerformed(java.awt.event.ActionEvent evt) {

                    new DlgYesNo(
                            SYSTools.xx("misc.questions.delete1") + "<br/><b>" + sysfile.getFilename()
                                    + "</b><br/>" + SYSTools.xx("misc.questions.delete2"),
                            new ImageIcon(getClass().getResource("/artwork/48x48/bw/trashcan_empty.png")),
                            new Closure() {
                                @Override
                                public void execute(Object o) {
                                    if (o.equals(JOptionPane.YES_OPTION)) {
                                        SYSFilesTools.deleteFile(sysfile);
                                        reloadTable();
                                    }
                                }
                            });

                }
            });
            menu.add(itemPopupDelete);
            itemPopupDelete.setEnabled(singleRowSelected);
        }

        menu.show(evt.getComponent(), (int) p.getX(), (int) p.getY());
    } else if (evt.getClickCount() == 2) {
        SYSFilesTools.handleFile(sysfile, Desktop.Action.OPEN);
    }

}

From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java

/**
 * {@inheritDoc}/*w ww .j ava  2 s . co m*/
 */
@Override
public <T extends BaseEntity> T update(T entity) {
    T updated;
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        em.getTransaction().begin();
        updated = em.merge(entity);
        em.getTransaction().commit();
    } catch (Exception ex) { // NOSONAR
        Transactions.markRollback(em);
        throw new JpaException(ex);
    } finally {
        Transactions.rollback(em);
        JpaUtil.closeEntityManager(em);
    }
    return updated;
}

From source file:org.opencastproject.scheduler.impl.persistence.SchedulerServiceDatabaseImpl.java

@Override
public void updateEvent(DublinCoreCatalog event) throws NotFoundException, SchedulerServiceDatabaseException {
    if (event == null) {
        throw new SchedulerServiceDatabaseException("Cannot update <null> event");
    }//from   w  w  w  .j a  v  a 2  s .co m
    Long eventId = Long.parseLong(event.getFirst(DublinCore.PROPERTY_IDENTIFIER));
    String dcXML;
    try {
        dcXML = serializeDublinCore(event);
    } catch (Exception e1) {
        logger.error("Could not serialize Dublin Core: {}", e1);
        throw new SchedulerServiceDatabaseException(e1);
    }
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        EventEntity entity = em.find(EventEntity.class, eventId);
        if (entity == null) {
            throw new NotFoundException("Event with ID " + eventId + " does not exist.");
        }
        entity.setEventDublinCore(dcXML);
        em.merge(entity);
        tx.commit();
    } catch (NotFoundException e) {
        throw e;
    } catch (Exception e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        logger.error("Could not store event: {}", e.getMessage());
        throw new SchedulerServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }

}

From source file:com.intuit.tank.dao.ScriptDao.java

/**
 * //from w  w  w  .  j  a v  a2  s.c  o  m
 * @{inheritDoc
 */
@Override
public Script saveOrUpdate(Script script) {
    MethodTimer mt = new MethodTimer(LOG, getClass(), "saveOrUpdate").start();
    int size = script.getScriptSteps().size();
    ScriptUtil.setScriptStepLabels(script);
    // try {
    LOG.info("persisting script " + script.getName() + " with id " + script.getId() + " into database");
    try {
        EntityManager em = getEntityManager();
        getEmProvider().get().startTrasaction(this);
        SerializedScriptStep serializedScriptStep = serialize(script.getScriptSteps());
        serializedScriptStep
                .setSerialzedData(Hibernate.createBlob(serializedScriptStep.getBytes(), getHibernateSession()));
        SerializedScriptStep serializedSteps = new SerializedScriptStepDao().saveOrUpdate(serializedScriptStep);
        script.setSerializedScriptStepId(serializedScriptStep.getId());
        if (script.getId() == 0) {
            em.persist(script);
        } else {
            script = em.merge(script);
        }
        LOG.debug("Saved Script Steps with id " + serializedSteps.getId() + " for script " + script.getId());
        getEmProvider().get().commitTransaction(this);
    } finally {
        getEmProvider().get().cleanup(this);
    }
    mt.markAndLog("Store script with " + size + " steps to database.");
    mt.endAndLog();
    return script;
}

From source file:org.opencastproject.scheduler.impl.persistence.SchedulerServiceDatabaseImpl.java

@Override
public void updateEventWithMetadata(long eventId, Properties caProperties)
        throws SchedulerServiceDatabaseException, NotFoundException {
    if (caProperties == null) {
        caProperties = new Properties();
    }/*w  w w  .  j ava2s . com*/
    String caSerialized;
    try {
        caSerialized = serializeProperties(caProperties);
    } catch (IOException e) {
        logger.error("Could not serialize properties: {}", e);
        throw new SchedulerServiceDatabaseException(e);
    }
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        EventEntity entity = em.find(EventEntity.class, eventId);
        if (entity == null) {
            throw new NotFoundException("Event with ID: " + eventId + " does not exist");
        }
        entity.setCaptureAgentMetadata(caSerialized);
        em.merge(entity);
        tx.commit();
    } catch (NotFoundException e) {
        logger.error("Event with ID '{}' does not exist", eventId);
        throw e;
    } catch (Exception e) {
        if (tx.isActive()) {
            tx.rollback();
        }
        logger.error("Could not store event metadata: {}", e.getMessage());
        throw new SchedulerServiceDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}