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.sigmah.server.servlet.exporter.models.ProjectReportModelHandler.java

/**
 * Save the section whith its sub sections and key questions
 * //from   w  ww  . jav a 2s  .c o  m
 * @param section
 *          the section to save
 * @param subSections
 *          the subsections to save.
 * @param keyQuestions
 *          the key question to save.
 * @param em
 *          the entity manager
 */
private static void saveSectionSubSectionKeyQuestions(ProjectReportModelSection section,
        List<ProjectReportModelSection> subSections, List<KeyQuestion> keyQuestions, EntityManager em) {
    if (keyQuestions != null) {
        saveSectionKeyQuestion(section, keyQuestions, em);
    }
    if (subSections != null) {
        for (ProjectReportModelSection subSection : subSections) {
            subSection.setParentSectionModelId(section.getId());
            List<ProjectReportModelSection> subSubSections = subSection.getSubSections();
            List<KeyQuestion> questions = subSection.getKeyQuestions();
            if (subSubSections != null || keyQuestions != null) {
                // Save sub section before its sub sections and its key questions
                subSection.setSubSections(null);
                subSection.setKeyQuestions(null);
                em.persist(subSection);
                // Save the sub sections and the key questions of the subsection
                saveSectionSubSectionKeyQuestions(subSection, subSubSections, questions, em);
                subSection.setSubSections(subSubSections);
                if (subSection != null) {
                    em.merge(subSection);
                }
            } else {
                if (subSection != null) {
                    em.persist(subSection);
                }
            }
        }
    }

}

From source file:br.com.i9torpedos.model.service.repository.BaseRepository.java

public T saveOrUpdate(T obj) throws PersistenceException {
    EntityManager em = EntityManagerUtil.getEntityManager();
    em.getTransaction().begin();//from   ww w .  j  ava2 s . c om
    Boolean situacao = false;

    if (obj != null) {

        try {
            // if (obj != null) {
            obj = em.merge(obj);

            log.info("Dados Atualizado com Sucesso. " + obj.getClass().getName());
            situacao = true;

            /*} else {
            em.persist(obj);
                    
            log.info("Dados Gravado com Sucesso. " + obj.getClass().getName());
            situacao = true;
            }*/

        } catch (Exception e) {
            situacao = false;
            log.fatal("Falha em Atualizar ou Gravar dados " + e.getMessage());

            //Devida a falha de Persistencia ira Realizar um Rolback
            em.getTransaction().rollback();
            throw new PersistenceException("Falha ao Persistir Dados", e);

        } finally {

            //se for verdadeiro ento realiza o commit e fecha meu entitymanager
            if (situacao) {
                em.getTransaction().commit();
                //em.flush();
                // em.clear();
            }
            em.close();
            log.info("EntityManager fechado com Sucesso. Metodo saveOrUpdate");
        }
    }

    return obj;

}

From source file:de.berlios.jhelpdesk.dao.jpa.UserDAOJpa.java

@Transactional(readOnly = false)
public void updatePasswordAndSalt(final User user, final String password) {
    this.jpaTemplate.execute(new JpaCallback<Object>() {
        public Object doInJpa(EntityManager em) throws PersistenceException {
            User u = em.find(User.class, user.getUserId());
            if (u != null) {
                u.setPassword(password); // TODO: zbada czy to ma sens (vide moppee)
                em.merge(u);
            }//w ww. j a  va2 s . c  om
            return null;
        }
    });
}

From source file:org.apereo.portal.layout.dao.jpa.JpaStylesheetDescriptorDao.java

@PortalTransactional
@Override//w ww .  j a v  a  2 s  . co m
public void deleteStylesheetDescriptor(IStylesheetDescriptor stylesheetDescriptor) {
    Validate.notNull(stylesheetDescriptor, "definition can not be null");

    final IStylesheetDescriptor persistentStylesheetDescriptor;
    final EntityManager entityManager = this.getEntityManager();
    if (entityManager.contains(stylesheetDescriptor)) {
        persistentStylesheetDescriptor = stylesheetDescriptor;
    } else {
        persistentStylesheetDescriptor = entityManager.merge(stylesheetDescriptor);
    }

    entityManager.remove(persistentStylesheetDescriptor);
}

From source file:org.jasig.portlet.blackboardvcportlet.dao.impl.ConferenceUserDaoImpl.java

@Override
@Transactional//  w  ww  . j a  v a 2 s  .  c  o m
public void deleteUser(ConferenceUser user) {
    Validate.notNull(user, "user can not be null");

    final EntityManager entityManager = this.getEntityManager();
    if (!entityManager.contains(user)) {
        user = entityManager.merge(user);
    }
    entityManager.remove(user);
}

From source file:com.sdl.odata.datasource.jpa.JPADataSource.java

@Override
public void delete(ODataUri uri, EntityDataModel entityDataModel) throws ODataException {
    Option<Object> entity = extractEntityWithKeys(uri, entityDataModel);

    if (entity.isDefined()) {
        Object jpaEntity = entityMapper.convertODataEntityToDS(entity.get(), entityDataModel);
        if (jpaEntity != null) {
            EntityManager entityManager = getEntityManager();
            EntityTransaction transaction = entityManager.getTransaction();
            try {
                transaction.begin();/*  ww w. j  a va2  s.  c o m*/

                Object attached = entityManager.merge(jpaEntity);
                entityManager.remove(attached);
            } catch (PersistenceException e) {
                LOG.error("Could not remove entity: {}", entity);
                throw new ODataDataSourceException("Could not remove entity", e);
            } finally {
                if (transaction.isActive()) {
                    transaction.commit();
                } else {
                    transaction.rollback();
                }
            }
        } else {
            throw new ODataDataSourceException("Could not remove entity, could not be loaded");
        }
    }
}

From source file:org.apereo.portal.groups.pags.dao.jpa.JpaPersonAttributesGroupDefinitionDao.java

@PortalTransactional
@Override/*from  w ww  .j  ava2  s .  com*/
public void deletePersonAttributesGroupDefinition(IPersonAttributesGroupDefinition definition) {
    Validate.notNull(definition, "definition can not be null");

    final IPersonAttributesGroupDefinition persistentDefinition;
    final EntityManager entityManager = this.getEntityManager();
    if (entityManager.contains(definition)) {
        persistentDefinition = definition;
    } else {
        persistentDefinition = entityManager.merge(definition);
    }
    entityManager.remove(persistentDefinition);
}

From source file:org.jasig.portal.groups.pags.dao.jpa.JpaPersonAttributesGroupDefinitionDao.java

@PortalTransactional
@Override// ww  w  .  jav a2  s.com
public IPersonAttributesGroupDefinition updatePersonAttributesGroupDefinition(
        IPersonAttributesGroupDefinition personAttributesGroupDefinition) {
    Validate.notNull(personAttributesGroupDefinition, "personAttributesGroupDefinition can not be null");

    final IPersonAttributesGroupDefinition persistentDefinition;
    final EntityManager entityManager = this.getEntityManager();
    if (entityManager.contains(personAttributesGroupDefinition)) {
        persistentDefinition = personAttributesGroupDefinition;
    } else {
        persistentDefinition = entityManager.merge(personAttributesGroupDefinition);
    }
    this.getEntityManager().persist(persistentDefinition);
    return persistentDefinition;
}

From source file:com.github.jrh3k5.membership.renewal.mailer.service.jpa.JpaMembershipService.java

private void updateMembership(EntityManager entityManager, JpaMembershipRecord membership) {
    final EntityTransaction transaction = entityManager.getTransaction();
    try {/*from  w  ww  .  j  av a2  s  .  c  o m*/
        transaction.begin();
        entityManager.merge(membership);
        transaction.commit();
    } catch (RuntimeException e) {
        transaction.rollback();
        throw e;
    }
}

From source file:controllers.modules.SetCoverBuilder.java

@BodyParser.Of(play.mvc.BodyParser.Json.class)
public static Result update(final UUID corpus, UUID setcover) {
    DocumentCorpus corpusObj = null;/*from  w  ww  .  jav a2  s.  co m*/
    if (corpus != null) {
        corpusObj = fetchResource(corpus, DocumentCorpus.class);
    }

    // make sure we have the right combination.
    DocumentSetCover setCoverObj = null;
    if (setcover != null) {
        setCoverObj = fetchResource(setcover, DocumentSetCover.class);
        if (corpusObj == null) {
            corpusObj = setCoverObj.getBaseCorpus();
        } else if (ObjectUtils.notEqual(corpusObj, setCoverObj.getBaseCorpus())) {
            throw new IllegalArgumentException();
        }
    } else if (corpusObj == null) {
        throw new IllegalArgumentException();
    }

    JsonNode jsonBody = request().body().asJson();
    if (jsonBody == null && setcover != null) {
        throw new IllegalArgumentException();
    }
    if (jsonBody == null) {
        jsonBody = JsonNodeFactory.instance.objectNode();
    }

    DocumentSetCoverModel setCoverVM = null;
    setCoverVM = Json.fromJson(jsonBody, DocumentSetCoverModel.class);
    final SetCoverFactory factory = (SetCoverFactory) setCoverVM.toFactory().setOwnerId(getUsername());

    // set the default title.
    if (setcover == null && StringUtils.isEmpty(factory.getTitle())) {
        factory.setTitle("Optimized " + corpusObj.getTitle());
    }

    SetCoverFactory tmpFactory = (SetCoverFactory) new SetCoverFactory().setStore(corpusObj)
            .setTitle(factory.getTitle()).setDescription(factory.getDescription())
            .setOwnerId(factory.getOwnerId());

    // make basic creation/updation first.
    if (setcover == null) {
        setCoverObj = tmpFactory.create();
        em().persist(setCoverObj);
        setCoverVM = (DocumentSetCoverModel) createViewModel(setCoverObj);

        // if this is a simple change, just return from here.
        if (ObjectUtils.equals(
                ObjectUtils.defaultIfNull(factory.getTokenizingOptions(), new TokenizingOptions()),
                new TokenizingOptions())
                && factory.getWeightCoverage() == SetCoverFactory.DEFAULT_WEIGHT_COVERAGE) {
            return created(setCoverVM.asJson());
        }
        setcover = setCoverObj.getIdentifier();
    } else if (!StringUtils.equals(StringUtils.defaultString(tmpFactory.getTitle(), setCoverObj.getTitle()),
            setCoverObj.getTitle())
            || !StringUtils.equals(
                    StringUtils.defaultString(tmpFactory.getDescription(), setCoverObj.getDescription()),
                    setCoverObj.getDescription())) {

        tmpFactory.setEm(em()).setExistingId(setcover);
        setCoverObj = tmpFactory.create();
        em().merge(setCoverObj);
        setCoverVM = (DocumentSetCoverModel) createViewModel(setCoverObj);
        setCoverVM.populateSize(em(), setCoverObj);

        // if this is a simple change, just return from here.
        if (ObjectUtils.equals(
                ObjectUtils.defaultIfNull(factory.getTokenizingOptions(), new TokenizingOptions()),
                ObjectUtils.defaultIfNull(setCoverObj.getTokenizingOptions(), new TokenizingOptions()))
                && ObjectUtils.equals(factory.getWeightCoverage(), ObjectUtils.defaultIfNull(
                        setCoverObj.getWeightCoverage(), SetCoverFactory.DEFAULT_WEIGHT_COVERAGE))) {
            return ok(setCoverVM.asJson());
        }
    }

    // get rid of any old progress observer tokens and create a new one.
    finalizeProgress(setCoverObj.getId());
    createProgressObserverToken(setCoverObj.getId());
    watchProgress(factory, "create", setCoverObj.getId());

    final Context ctx = Context.current();
    final UUID setCoverId = setcover;

    Akka.future(new Callable<DocumentSetCover>() {
        @Override
        public DocumentSetCover call() throws Exception {
            try {
                return execute(new SareTxRunnable<DocumentSetCover>() {
                    @Override
                    public DocumentSetCover run(EntityManager em) throws Throwable {
                        bindEntityManager(em);
                        Context.current.set(ctx);

                        DocumentSetCover setCoverObj = null;
                        UUID corpusId = corpus;
                        if (corpusId == null) {
                            setCoverObj = fetchResource(setCoverId, DocumentSetCover.class);
                            corpusId = setCoverObj.getBaseCorpus().getIdentifier();
                        }

                        factory.setStore(fetchResource(corpusId, DocumentCorpus.class))
                                .setExistingId(setCoverId).setEm(em);

                        List<SetCoverDocument> oldDocuments = Lists.newArrayList(setCoverObj.getAllDocuments());
                        setCoverObj = factory.create();

                        em.flush();
                        em.merge(setCoverObj);
                        em.getTransaction().commit();
                        em.clear();

                        em.getTransaction().begin();
                        for (SetCoverDocument oldDocument : oldDocuments) {
                            if (Iterables.find(setCoverObj.getAllDocuments(), Predicates.equalTo(oldDocument),
                                    null) == null) {
                                SetCoverDocument tmpDocument = em.find(SetCoverDocument.class,
                                        oldDocument.getId());
                                em.remove(tmpDocument);
                            }
                        }

                        return setCoverObj;
                    }
                }, ctx);
            } catch (Throwable e) {
                Logger.error(LoggedAction.getLogEntry(ctx, "failed to build set cover"), e);
                throw new IllegalArgumentException(e);
            } finally {
                setProgressFinished(UuidUtils.toBytes(setCoverId));
            }
        }
    });

    return ok(setCoverVM.asJson());
}