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.rhq.enterprise.server.drift.JPADriftServerBeanTest.java

public void copyChangeSet() {
    // first create the change set that will be copied
    final JPADriftChangeSet changeSet = new JPADriftChangeSet(null, 0, COVERAGE, null);
    changeSet.setDriftHandlingMode(normal);

    final JPADrift drift1 = new JPADrift(changeSet, "drift.1", FILE_ADDED, null, driftFile1);
    final JPADrift drift2 = new JPADrift(changeSet, "drift.2", FILE_ADDED, null, driftFile2);

    final JPADriftSet driftSet = new JPADriftSet();
    driftSet.addDrift(drift1);//from w w w. jav a  2 s  .com
    driftSet.addDrift(drift2);

    // next create the drift definition
    final DriftDefinition driftDef = new DriftDefinition(new Configuration());
    driftDef.setName("test::copyChangeSet");
    driftDef.setEnabled(true);
    driftDef.setDriftHandlingMode(normal);
    driftDef.setInterval(2400L);
    driftDef.setBasedir(new DriftDefinition.BaseDirectory(fileSystem, "/foo/bar/test"));
    driftDef.setResource(resource);

    // persist the change set and drift definition
    executeInTransaction(new TransactionCallback() {
        @Override
        public void execute() throws Exception {
            EntityManager em = getEntityManager();
            em.persist(changeSet);
            em.persist(driftDef);
            em.persist(driftSet);
            changeSet.setInitialDriftSet(driftSet);
            em.merge(changeSet);
        }
    });

    jpaDriftServer.copyChangeSet(getOverlord(), changeSet.getId(), driftDef.getId(), resource.getId());

    // verify that the change set was created for the definition
    JPADriftChangeSetCriteria criteria = new JPADriftChangeSetCriteria();
    criteria.addFilterDriftDefinitionId(driftDef.getId());
    criteria.addFilterCategory(COVERAGE);

    PageList<JPADriftChangeSet> changeSets = jpaDriftServer.findDriftChangeSetsByCriteria(getOverlord(),
            criteria);

    assertEquals("Expected to get back one change set", 1, changeSets.size());

    JPADriftChangeSet newChangeSet = changeSets.get(0);
    Set<JPADrift> expectedDrifts = new HashSet<JPADrift>(asList(drift1, drift2));
    Set<JPADrift> actualDrifts = newChangeSet.getDrifts();

    AssertUtils.assertCollectionMatchesNoOrder("The change set drifts were not copied correctly",
            expectedDrifts, actualDrifts, "changeSet", "newDriftFile");
}

From source file:op.care.med.inventory.DlgCloseStock.java

private void save() {
    EntityManager em = OPDE.createEM();
    try {//  w w  w. ja va2  s .  co  m
        em.getTransaction().begin();

        final MedStock myStock = em.merge(medStock);
        em.lock(myStock, LockModeType.OPTIMISTIC);
        em.lock(em.merge(myStock.getInventory().getResident()), LockModeType.OPTIMISTIC);
        em.lock(em.merge(myStock.getInventory()), LockModeType.OPTIMISTIC);

        OPDE.important("StockID: " + myStock.getID() + " " + SYSTools.xx("misc.msg.closed"));
        OPDE.important("UID: " + OPDE.getLogin().getUser().getUID());

        MedStock nextBest = null;
        if (cmbBestID.getSelectedIndex() > 0) {
            nextBest = em.merge((MedStock) cmbBestID.getSelectedItem());
            OPDE.important(SYSTools.xx("nursingrecords.prescription.dlgCloseStock.LOG.STATE_EDIT_EMPTY_SOON1")
                    + ": " + nextBest.getID());
            em.lock(nextBest, LockModeType.OPTIMISTIC);
            myStock.setNextStock(nextBest);
        }

        if (rbStellen.isSelected()) {
            BigDecimal inhalt = new BigDecimal(Double.parseDouble(txtLetzte.getText().replace(",", ".")));
            MedStockTools.setStockTo(em, myStock, inhalt,
                    SYSTools.xx("nursingrecords.prescription.dlgCloseStock.TX.STATE_EDIT_EMPTY_SOON"),
                    MedStockTransactionTools.STATE_EDIT_EMPTY_SOON);
            myStock.setState(MedStockTools.STATE_WILL_BE_CLOSED_SOON);
            OPDE.important(SYSTools.xx("nursingrecords.prescription.dlgCloseStock.LOG.STATE_EDIT_EMPTY_SOON1")
                    + ": " + inhalt);
        } else {
            if (rbGefallen.isSelected()) {
                MedStockTools.close(em, myStock,
                        SYSTools.xx(
                                "nursingrecords.prescription.dlgCloseStock.TX.STATE_EDIT_EMPTY_BROKEN_OR_LOST"),
                        MedStockTransactionTools.STATE_EDIT_EMPTY_BROKEN_OR_LOST);
                OPDE.important(SYSTools
                        .xx("nursingrecords.prescription.dlgCloseStock.LOG.STATE_EDIT_EMPTY_BROKEN_OR_LOST"));
            } else if (rbAbgelaufen.isSelected()) {
                MedStockTools.close(em, myStock,
                        SYSTools.xx(
                                "nursingrecords.prescription.dlgCloseStock.TX.STATE_EDIT_EMPTY_PAST_EXPIRY"),
                        MedStockTransactionTools.STATE_EDIT_EMPTY_PAST_EXPIRY);
                OPDE.important(SYSTools
                        .xx("nursingrecords.prescription.dlgCloseStock.LOG.STATE_EDIT_EMPTY_PAST_EXPIRY"));
            } else {
                MedStockTools.close(em, myStock,
                        SYSTools.xx("nursingrecords.prescription.dlgCloseStock.TX.STATE_EDIT_EMPTY_NOW"),
                        MedStockTransactionTools.STATE_EDIT_EMPTY_NOW);
                OPDE.important(
                        SYSTools.xx("nursingrecords.prescription.dlgCloseStock.LOG.STATE_EDIT_EMPTY_NOW"));
            }
        }

        em.getTransaction().commit();

        medStock = myStock;

    } catch (javax.persistence.OptimisticLockException 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();
    }

    dispose();
}

From source file:edu.vt.middleware.gator.JpaConfigManager.java

/** {@inheritDoc}. */
@Transactional(propagation = Propagation.REQUIRED)
public void deletePermissions(final ProjectConfig project, final int permissionId) {
    final EntityManager em = getEntityManager();
    if (logger.isDebugEnabled()) {
        logger.debug(String.format("Deleting permission ID=%s from %s.", project, permissionId));
    }//www . ja va  2s  .  c  o m
    project.removePermission(project.getPermission(permissionId));
    project.setModifiedDate(Calendar.getInstance());
    em.merge(project);
}

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

public void saveProfile(UserProfile profile) {
    EntityManager em = emf.createEntityManager();
    try {/*from   w  ww  .  j  a v  a  2s.  com*/
        em.getTransaction().begin();
        if (profile.profileId == null) {
            em.persist(profile);
        } else {
            em.merge(profile);
        }
        em.getTransaction().commit();
    } finally {
        em.close();
    }
}

From source file:org.apereo.portal.portlet.dao.jpa.JpaMarketplaceRatingDao.java

/**
 * This method will either create a new rating or update an
 * existing rating//from w  w  w .  j ava 2  s.  c  o m
 * 
 * @param  Must not be null
 * @return the attached entity
 * 
 */
@Override
@PortalTransactional
public IMarketplaceRating createOrUpdateRating(IMarketplaceRating marketplaceRatingImplementation) {
    Validate.notNull(marketplaceRatingImplementation, "MarketplaceRatingImpl must not be null");
    final EntityManager entityManager = this.getEntityManager();
    IMarketplaceRating temp = this.getRating(marketplaceRatingImplementation.getMarketplaceRatingPK());
    if (!entityManager.contains(marketplaceRatingImplementation) && temp != null) {
        //Entity is not managed and there is a rating for this portlet/user - update needed
        temp = entityManager.merge(marketplaceRatingImplementation);
    } else {
        //Entity is either already managed or doesn't exist - create needed
        temp = marketplaceRatingImplementation;
    }
    entityManager.persist(temp);
    return temp;
}

From source file:org.sigmah.server.endpoint.gwtrpc.PasswordManagementServlet.java

@Override
@Transactional//from w w  w  .  ja v a 2 s. c o  m
public void updatePassword(String email, String password) throws Exception {

    final EntityManager entityManager = injector.getInstance(EntityManager.class);

    final Query query = entityManager.createQuery("SELECT u FROM User u WHERE u.email = :email");
    query.setParameter("email", email);

    final User user = (User) query.getSingleResult();

    final String hashedPassword = BCrypt.hashpw(password, BCrypt.gensalt());
    user.setHashedPassword(hashedPassword);

    // disactivate password change key
    user.setChangePasswordKey(null);

    entityManager.merge(user);
    log.info(String.format("User's(%s) password has been updated using password reset link", email));
}

From source file:org.eclipse.jubula.client.core.persistence.Persistor.java

/**
 * /*from   w  w  w  .j  a  va 2  s  . co  m*/
 * @param em
 *            entity manager
 * @throws PersistenceException
 *             if we blow up
 */
private static void createOrUpdateDBVersion(EntityManager em) throws PersistenceException {
    EntityTransaction tx = null;
    try {
        tx = em.getTransaction();
        tx.begin();

        try {
            DBVersionPO version = (DBVersionPO) em.createQuery("select version from DBVersionPO as version") //$NON-NLS-1$
                    .getSingleResult();
            version.setMajorVersion(IVersion.JB_DB_MAJOR_VERSION);
            version.setMinorVersion(IVersion.JB_DB_MINOR_VERSION);
            em.merge(version);
        } catch (NoResultException nre) {
            em.merge(new DBVersionPO(IVersion.JB_DB_MAJOR_VERSION, IVersion.JB_DB_MINOR_VERSION));
        }

        tx.commit();
    } catch (PersistenceException pe) {
        if (tx != null) {
            tx.rollback();
        }
        throw pe;
    }
}

From source file:org.apache.juddi.replication.ReplicationNotifier.java

/**
 * Note: this is for locally originated changes only, see null null null         {@link org.apache.juddi.api.impl.UDDIReplicationImpl.PullTimerTask#PersistChangeRecord PersistChangeRecord
 * } for how remote changes are processed
 *
 * @param j must be one of the UDDI save APIs
 *
 *//* ww  w  .j a v  a 2s  . c om*/
protected void ProcessChangeRecord(org.apache.juddi.model.ChangeRecord j) {
    //store and convert the changes to database model

    //TODO need a switch to send the notification without persisting the record
    //this is to support multihop notifications
    EntityManager em = PersistenceManager.getEntityManager();
    EntityTransaction tx = null;
    try {
        tx = em.getTransaction();
        tx.begin();
        j.setIsAppliedLocally(true);
        em.persist(j);
        j.setOriginatingUSN(j.getId());
        em.merge(j);
        log.info("CR saved locally, it was from " + j.getNodeID() + " USN:" + j.getOriginatingUSN() + " Type:"
                + j.getRecordType().name() + " Key:" + j.getEntityKey() + " Local id:" + j.getId());
        tx.commit();
    } catch (Exception ex) {
        log.fatal("unable to store local change record locally!!", ex);
        if (tx != null && tx.isActive()) {
            tx.rollback();
        }
        JAXB.marshal(MappingModelToApi.mapChangeRecord(j), System.out);
    } finally {
        em.close();
    }

    log.debug("ChangeRecord: " + j.getId() + "," + j.getEntityKey() + "," + j.getNodeID() + ","
            + j.getOriginatingUSN() + "," + j.getRecordType().toString());
    SendNotifications(j.getId(), j.getNodeID(), false);

}

From source file:org.opencastproject.messages.MailService.java

public static MessageTemplateDto mergeMessageTemplate(MessageTemplate template, String organization,
        EntityManager em) {
    ArrayList<CommentDto> comments = new ArrayList<CommentDto>();
    for (Comment c : template.getComments()) {
        comments.add(CommentDatabaseUtils.mergeComment(c, em));
    }/*from w  w w  . j a va 2  s.c o  m*/

    Option<MessageTemplateDto> dtoOption = findMessageTemplate(option(template.getId()), template.getName(),
            organization, em);
    MessageTemplateDto dto;
    if (dtoOption.isSome()) {
        dto = dtoOption.get();
        dto.setName(template.getName());
        dto.setType(template.getType().getType());
        dto.setCreator(template.getCreator().getUsername());
        dto.setSubject(template.getSubject());
        dto.setBody(template.getBody());
        dto.setCreationDate(template.getCreationDate());
        dto.setComments(comments);
        dto.setHidden(template.isHidden());
        em.merge(dto);
    } else {
        dto = new MessageTemplateDto(template.getName(), organization, template.getCreator().getUsername(),
                template.getSubject(), template.getBody(), template.getType().getType(),
                template.getCreationDate(), comments);
        dto.setHidden(template.isHidden());
        em.persist(dto);
    }
    return dto;
}

From source file:org.jasig.cas.ticket.registry.support.JpaLockingStrategy.java

private boolean acquire(final EntityManager em, Lock lock) {
    lock.setUniqueId(uniqueId);/*  w ww.  j a va2  s.c  om*/
    if (lockTimeout > 0) {
        final Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, lockTimeout);
        lock.setExpirationDate(cal.getTime());
    } else {
        lock.setExpirationDate(null);
    }
    boolean success = false;
    try {
        if (lock.getApplicationId() != null) {
            lock = em.merge(lock);
        } else {
            lock.setApplicationId(applicationId);
            em.persist(lock);
        }
        success = true;
    } catch (PersistenceException e) {
        success = false;
        if (logger.isDebugEnabled()) {
            logger.debug("{} could not obtain {} lock.", new Object[] { uniqueId, applicationId, e });
        } else {
            logger.info("{} could not obtain {} lock.", uniqueId, applicationId);
        }
    }
    return success;
}