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:cz.fi.muni.pa165.daoImpl.TroopDAOImpl.java

@Override
public void removeTroop(Troop troop) throws IllegalArgumentException {
    if (troop == null) {
        throw new IllegalArgumentException("Troop can't be null.");
    }//  ww w  .j av a  2  s . co m
    if (troop.getId() == null) {
        throw new IllegalArgumentException("Troop is not present in DB.");
    }
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();
    Troop present = em.find(Troop.class, troop.getId());
    em.getTransaction().commit();

    if (present == null) {
        throw new IllegalArgumentException("Troop is not present in DB.");
    } else {
        em.getTransaction().begin();
        em.remove(em.contains(troop) ? troop : em.merge(troop));
        em.getTransaction().commit();
    }
    em.close();
}

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

/**
 * Save elements of imported project report model
 * /*w w  w  . java  2 s . co m*/
 * @param projectReportModel
 *            the imported project report model
 * @param em
 *            the entity manager
 */
public static void saveProjectReportModelElement(ProjectReportModel projectReportModel, EntityManager em) {

    //Save the sections on the project report model
    List<ProjectReportModelSection> sections = projectReportModel.getSections();
    if (sections != null) {
        // Save the project report model without the sections;
        projectReportModel.setSections(null);
        em.persist(projectReportModel);
        // Save the project report sections with the parent project report (saved above)
        for (ProjectReportModelSection section : sections) {
            section.setProjectModelId(projectReportModel.getId());
            List<ProjectReportModelSection> subSections = section.getSubSections();
            List<KeyQuestion> keyQuestions = section.getKeyQuestions();
            if (subSections != null || keyQuestions != null) {
                //Save the section without the sub sections or the key questions
                section.setSubSections(null);
                section.setKeyQuestions(null);
                em.persist(section);
                //Save the sub sections and the key questions
                saveSectionSubSectionKeyQuestions(section, subSections, keyQuestions, em);
                section.setSubSections(subSections);

                em.merge(section);
            } else {
                em.persist(section);
            }
        }
        // Set the sections saved above to the project report model
        projectReportModel.setSections(sections);
    }
}

From source file:de.iai.ilcd.model.dao.AbstractDao.java

/**
 * Default remove: bring back to persistence context if required and delete
 * //from   w ww . j a  v a2 s.c  o  m
 * @param objs
 *            objects to remove
 * @return removed objects
 * @throws Exception
 *             on errors (transaction is being rolled back)
 */
public Collection<T> remove(Collection<T> objs) throws Exception {
    if (objs == null || objs.isEmpty()) {
        return null;
    }
    Collection<T> res = new ArrayList<T>();
    EntityManager em = PersistenceUtil.getEntityManager();
    EntityTransaction t = em.getTransaction();

    try {
        t.begin();
        for (T obj : objs) {
            T tmp = em.contains(obj) ? obj : em.merge(obj);
            em.remove(tmp);
            res.add(tmp);
        }
        t.commit();
        return res;
    } catch (Exception e) {
        t.rollback();
        throw e;
    }
}

From source file:nl.b3p.kaartenbalie.struts.WMSUrlCreatorAction.java

public ActionForward getMapUrl(ActionMapping mapping, DynaValidatorForm dynaForm, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    if (!isTokenValid(request)) {
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, TOKEN_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }/*from   w  w w  . j av a 2  s .co m*/

    ActionErrors errors = dynaForm.validate(mapping, request);
    if (!errors.isEmpty()) {
        super.addMessages(request, errors);
        prepareMethod(dynaForm, request, EDIT, LIST);
        addAlternateMessage(mapping, request, VALIDATION_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }

    //Create the String
    String[] layers = (String[]) dynaForm.get("sortedLayers");
    String projectie = (String) dynaForm.get("selectedProjectie");
    String bbox = (String) dynaForm.get("bbox");
    Integer height = (Integer) dynaForm.get("height");
    Integer width = (Integer) dynaForm.get("width");
    String format = (String) dynaForm.get("selectedFormat");
    String pUrl = (String) dynaForm.get("personalUrl");

    if (layers.length == 0) {
        prepareMethod(dynaForm, request, LIST, LIST);
        addAlternateMessage(mapping, request, NO_LAYERS_SELECTED_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }

    /*
     * Get the URL to start with
     */
    User user = (User) request.getUserPrincipal();
    if (user == null) {
        prepareMethod(dynaForm, request, LIST, LIST);
        addAlternateMessage(mapping, request, UNKNOWN_SES_USER_ERROR_KEY);
        return getAlternateForward(mapping, request);
    }

    StringBuffer layerString = new StringBuffer();
    for (int i = 0; i < layers.length; i++) {
        layerString.append(layers[i]);
        layerString.append(",");
    }
    String layer = layerString.substring(0, layerString.lastIndexOf(","));

    StringBuffer getMapUrl = new StringBuffer(user.getPersonalURL(request));
    getMapUrl.append("?");
    getMapUrl.append(OGCConstants.WMS_SERVICE);
    getMapUrl.append("=");
    getMapUrl.append(OGCConstants.WMS_SERVICE_WMS);
    getMapUrl.append("&");
    getMapUrl.append(OGCConstants.WMS_VERSION);
    getMapUrl.append("=");
    getMapUrl.append(OGCConstants.WMS_VERSION_111);
    getMapUrl.append("&");
    getMapUrl.append(OGCConstants.WMS_REQUEST);
    getMapUrl.append("=");
    getMapUrl.append(OGCConstants.WMS_REQUEST_GetMap);
    getMapUrl.append("&");
    getMapUrl.append(OGCConstants.WMS_PARAM_LAYERS);
    getMapUrl.append("=");
    getMapUrl.append(layer);
    getMapUrl.append("&");
    getMapUrl.append(OGCConstants.WMS_PARAM_BBOX);
    getMapUrl.append("=");
    getMapUrl.append(bbox);
    getMapUrl.append("&");
    getMapUrl.append(OGCConstants.WMS_PARAM_SRS);
    getMapUrl.append("=");
    getMapUrl.append(projectie);
    getMapUrl.append("&");
    getMapUrl.append(OGCConstants.WMS_PARAM_HEIGHT);
    getMapUrl.append("=");
    getMapUrl.append(height);
    getMapUrl.append("&");
    getMapUrl.append(OGCConstants.WMS_PARAM_WIDTH);
    getMapUrl.append("=");
    getMapUrl.append(width);
    getMapUrl.append("&");
    getMapUrl.append(OGCConstants.WMS_PARAM_FORMAT);
    getMapUrl.append("=");
    getMapUrl.append(format);
    getMapUrl.append("&");
    getMapUrl.append(OGCConstants.WMS_PARAM_BGCOLOR);
    getMapUrl.append("=");
    getMapUrl.append("0xF0F0F0");
    getMapUrl.append("&");
    getMapUrl.append(OGCConstants.WMS_PARAM_EXCEPTIONS);
    getMapUrl.append("=");
    getMapUrl.append(OGCConstants.WMS_PARAM_EXCEPTION_INIMAGE);
    getMapUrl.append("&");
    getMapUrl.append(OGCConstants.WMS_PARAM_STYLES);
    getMapUrl.append("=");

    user.setDefaultGetMap(getMapUrl.toString());

    log.debug("Getting entity manager ......");
    EntityManager em = getEntityManager();
    if (user.getId() == null) {
        em.persist(user);
    } else {
        em.merge(user);
    }
    em.flush();

    populateForm(getMapUrl.toString(), dynaForm, request);
    prepareMethod(dynaForm, request, LIST, EDIT);
    addDefaultMessage(mapping, request, ACKNOWLEDGE_MESSAGES);
    return getDefaultForward(mapping, request);
}

From source file:org.eclipse.jubula.client.core.businessprocess.TestresultSummaryBP.java

/**
 * perform model changes//  w  ww  . jav  a2 s .  c o m
 * 
 * @param selectedSummary the summary to change the comment for
 * @param newTitle the new comment title
 * @param newDetails the new comment details
 */
public void setCommentTitleAndDetails(ITestResultSummaryPO selectedSummary, String newTitle,
        String newDetails) {

    Persistor persistor = Persistor.instance();
    final EntityManager sess = persistor.openSession();
    try {
        final EntityTransaction tx = persistor.getTransaction(sess);

        ITestResultSummaryPO summary = sess.merge(selectedSummary);

        summary.setCommentTitle(newTitle);
        summary.setCommentDetail(newDetails);

        persistor.commitTransaction(sess, tx);
        DataEventDispatcher.getInstance().fireTestresultSummaryChanged(summary, DataState.StructureModified);
    } catch (PMException e) {
        throw new JBFatalException(Messages.StoringOfMetadataFailed, e, MessageIDs.E_DATABASE_GENERAL);
    } catch (ProjectDeletedException e) {
        throw new JBFatalException(Messages.StoringOfMetadataFailed, e, MessageIDs.E_PROJECT_NOT_FOUND);
    } finally {
        persistor.dropSession(sess);
    }
}

From source file:org.sigmah.server.servlet.exporter.models.ProjectReportModelHandler.java

/**
 * Save elements of imported project report model
 * //from  w w w  .  j  a va 2s.c o m
 * @param projectReportModel
 *          the imported project report model
 * @param em
 *          the entity manager
 */
public static void saveProjectReportModelElement(ProjectReportModel projectReportModel, EntityManager em) {

    // Save the sections on the project report model
    List<ProjectReportModelSection> sections = projectReportModel.getSections();
    if (sections != null) {
        // Save the project report model without the sections;
        projectReportModel.setSections(null);
        em.persist(projectReportModel);
        // Save the project report sections with the parent project report (saved above)
        for (ProjectReportModelSection section : sections) {
            section.setProjectModelId(projectReportModel.getId());
            List<ProjectReportModelSection> subSections = section.getSubSections();
            List<KeyQuestion> keyQuestions = section.getKeyQuestions();
            if (subSections != null || keyQuestions != null) {
                // Save the section without the sub sections or the key questions
                section.setSubSections(null);
                section.setKeyQuestions(null);
                em.persist(section);
                // Save the sub sections and the key questions
                saveSectionSubSectionKeyQuestions(section, subSections, keyQuestions, em);
                section.setSubSections(subSections);

                em.merge(section);
            } else {
                em.persist(section);
            }
        }
        // Set the sections saved above to the project report model
        projectReportModel.setSections(sections);
    }
}

From source file:com.epam.training.taranovski.web.project.repository.implementation.OfferBidRepositoryImplementation.java

@Override
public boolean delete(OfferBid something) {
    EntityManager em = entityManagerFactory.createEntityManager();
    boolean success = true;
    OfferBid managedManagedOfferBid = null;
    try {//from   w ww  .  j a va  2  s .  c o m
        em.getTransaction().begin();
        managedManagedOfferBid = em.merge(something);
        em.remove(managedManagedOfferBid);
        em.getTransaction().commit();

        success = true;
    } catch (RuntimeException e) {
        Logger.getLogger(OfferBidRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
            success = false;
        }
        em.close();
    }

    return success;
}

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

/**
 * @param entity to delete - can not be null
 *//*from   ww  w . java2s.  c o m*/
@Override
@PortalTransactional
public void deleteRating(IMarketplaceRating marketplaceRatingImplementation) {
    Validate.notNull(marketplaceRatingImplementation, "marketplaceRatingImplementation can not be null");
    final IMarketplaceRating persistantMarketplaceRatingImpl;
    final EntityManager entityManager = this.getEntityManager();
    if (entityManager.contains(marketplaceRatingImplementation)) {
        persistantMarketplaceRatingImpl = marketplaceRatingImplementation;
    } else {
        persistantMarketplaceRatingImpl = entityManager.merge(marketplaceRatingImplementation);
    }
    entityManager.remove(persistantMarketplaceRatingImpl);
}

From source file:fr.xebia.demo.wicket.blog.service.GenericService.java

public T update(T entity) throws ServiceException {
    try {/*from   ww w  .  jav  a 2s  .c  o m*/
        EntityManager entityManager = currentEntityManager();
        entityManager.getTransaction().begin();
        T loadedObject = entityManager.find(getObjectClass(), getObjectId(entity));
        T mergedEntity = merge(loadedObject, entity);
        T updatedEntity = entityManager.merge(mergedEntity);
        commitTransaction();
        return updatedEntity;
    } catch (PersistenceException e) {
        logger.error(e.getCause(), e);
        rollbackTransaction();
        throw new ServiceException("Can't update object", e);
    } finally {
        closeEntityManager();
    }
}

From source file:org.apache.james.user.jpa.JPAUsersRepository.java

/**
 * Update the repository with the specified user object. A user object with
 * this username must already exist.//w w  w .  j a  v a  2s  .c om
 * 
 * @throws UsersRepositoryException
 */
public void updateUser(User user) throws UsersRepositoryException {
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    final EntityTransaction transaction = entityManager.getTransaction();
    try {
        if (contains(user.getUserName())) {
            transaction.begin();
            entityManager.merge(user);
            transaction.commit();
        } else {
            getLogger().debug("User not found");
            throw new UsersRepositoryException("User " + user.getUserName() + " not found");
        }
    } catch (PersistenceException e) {
        getLogger().debug("Failed to update user", e);
        if (transaction.isActive()) {
            transaction.rollback();
        }
        throw new UsersRepositoryException("Failed to update user " + user.getUserName(), e);
    } finally {
        entityManager.close();
    }
}