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:fr.mby.opa.picsimpl.dao.DbProposalDao.java

/**
 * @param proposalBag//www  .j a v a2  s  .  co  m
 * @return
 */
protected ProposalBag _updateProposalBagInternal(final ProposalBag proposalBag) {
    final TxCallbackReturn<ProposalBag> txCallback = new TxCallbackReturn<ProposalBag>(this.getEmf()) {

        @Override
        protected ProposalBag executeInTransaction(final EntityManager em) {
            final ProposalBag updatedBag = em.merge(proposalBag);
            em.flush();
            em.refresh(updatedBag);
            return updatedBag;
        }
    };

    final ProposalBag updatedBag = txCallback.getReturnedValue();
    return updatedBag;
}

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

@Override
public boolean update(Employee employee) {
    EntityManager em = entityManagerFactory.createEntityManager();
    boolean success = true;
    try {//from  w  w  w  .  j  a va  2  s  . c  o  m
        em.getTransaction().begin();

        em.merge(employee);
        em.flush();

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

    return success;
}

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

@Override
public boolean update(Vacancy vacancy) {
    EntityManager em = entityManagerFactory.createEntityManager();
    boolean success = true;
    try {/*from   www. j av a  2  s .co m*/
        em.getTransaction().begin();
        em.merge(vacancy);
        em.getTransaction().commit();
        success = true;
    } catch (RuntimeException e) {
        Logger.getLogger(VacancyRepositoryImplementation.class.getName()).info(e);
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
            success = false;
        }
        em.close();
    }

    return success;
}

From source file:fr.mby.opa.picsimpl.dao.DbProposalDao.java

@Override
public ProposalBranch updateBranch(final ProposalBranch branch) {
    Assert.notNull(branch, "No ProposalBag supplied !");
    Assert.notNull(branch.getId(), "Id should be set for update !");

    final TxCallbackReturn<ProposalBranch> txCallback = new TxCallbackReturn<ProposalBranch>(this.getEmf()) {

        @Override//w w w  .  ja va2  s  .  co  m
        protected ProposalBranch executeInTransaction(final EntityManager em) {
            final ProposalBranch updatedBranch = em.merge(branch);
            em.flush();
            em.refresh(updatedBranch);
            return updatedBranch;
        }
    };

    final ProposalBranch updatedBag = txCallback.getReturnedValue();
    return updatedBag;
}

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

@PortalTransactional
@Override/*from   w  w w .ja  v a 2  s.  co m*/
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:ejb.bean.UsuarioDAOJPAImplBean.java

/**Mtodo para a atualizao do usurio
 * @author Richel Sensineli//from  w  w w  .  ja  v  a 2  s.c  o  m
 * @param id int - ID do usurio
 * @param nome String - Nome do usurio
 * @param sobrenome String - Nome do usurio
 */
@Override
public void updateUsuario(final int id, final String nome, final String sobrenome)
        throws UsuarioNaoEncontradoException {
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("UsuarioPU");
    EntityManager em = emf.createEntityManager();

    UsuarioImpl user = em.find(UsuarioImpl.class, id);
    user.setNome(nome);
    user.setSobrenome(sobrenome);

    em.getTransaction().begin();
    try {
        em.merge(user);
        em.getTransaction().commit();
    } catch (Exception e) {
        e.printStackTrace();
        em.getTransaction().rollback();
    }

    em.clear();
    em.close();
    emf.close();
}

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

/**
 * @param marketplaceRatingPK the primary key of the entity you want
 * @return an attached entity if found, null otherwise
 *//*from  w  w w  .  j  av a  2  s  .  com*/
@PortalTransactionalReadOnly
@OpenEntityManager(unitName = PERSISTENCE_UNIT_NAME)
public IMarketplaceRating getRating(MarketplaceRatingPK marketplaceRatingPK) {
    final MarketplaceRatingPK tempRatingPK = marketplaceRatingPK;
    MarketplaceRatingImpl temp = new MarketplaceRatingImpl();
    temp.setMarketplaceRatingPK(marketplaceRatingPK);
    final EntityManager entityManager = this.getEntityManager();
    if (entityManager.contains(temp)) {
        temp = entityManager.merge(temp);
        return temp;
    } else {
        final TypedQuery<MarketplaceRatingImpl> query = this.createQuery(
                this.createCriteriaQuery(new Function<CriteriaBuilder, CriteriaQuery<MarketplaceRatingImpl>>() {
                    @Override
                    public CriteriaQuery<MarketplaceRatingImpl> apply(CriteriaBuilder input) {
                        final CriteriaQuery<MarketplaceRatingImpl> criteriaQuery = input
                                .createQuery(MarketplaceRatingImpl.class);
                        final Root<MarketplaceRatingImpl> definitionRoot = criteriaQuery
                                .from(MarketplaceRatingImpl.class);
                        Predicate conditionUser = input.equal(
                                definitionRoot.get("marketplaceRatingPK").get("userName"),
                                tempRatingPK.getUserName());
                        Predicate conditionPortlet = input.equal(
                                definitionRoot.get("marketplaceRatingPK").get("portletDefinition"),
                                tempRatingPK.getPortletDefinition());
                        Predicate allConditions = input.and(conditionPortlet, conditionUser);
                        criteriaQuery.where(allConditions);
                        return criteriaQuery;
                    }
                }));
        List<MarketplaceRatingImpl> results = query.getResultList();
        if (!results.isEmpty()) {
            return results.get(0);
        } else {
            return null;
        }
    }
}

From source file:org.wte4j.persistence.WordTemplateRepositoryTest.java

@Test
@Transactional/*from   ww w .j  a  v a  2  s  . com*/
public void errorsWithFileStore() throws Exception {
    WordTemplate<?> template = unlockedTemplate();
    FileStore fileStore = mock(FileStore.class);
    repository.setFileStore(fileStore);
    EntityManager entityManager = mock(EntityManager.class);
    when(entityManager.merge(any())).thenThrow(new PersistenceException());
    repository.em = entityManager;
    try {
        repository.persist(template);
        fail("Exception expected");
    } catch (Exception e) {
        verifyZeroInteractions(fileStore);
    }
}

From source file:org.wte4j.impl.WordTemplateRepositoryTest.java

@Test
@Transactional/*from www . ja v a 2  s.  c  o m*/
public void errorsWithFileStore() throws Exception {
    WordTemplate<?> template = unlockedTemplate();

    FileStore fileStore = mock(FileStore.class);
    repository.setFileStore(fileStore);

    EntityManager entityManager = mock(EntityManager.class);
    when(entityManager.merge(any())).thenThrow(new PersistenceException());
    repository.em = entityManager;
    try {
        repository.persist(template);
        fail("Exception expected");
    } catch (Exception e) {
        verifyZeroInteractions(fileStore);
    }
}

From source file:op.care.med.structure.DlgProduct.java

private void btnOKActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOKActionPerformed

    if (!saveOK())
        return;/*w  w w. ja  va  2 s .com*/

    EntityManager em = OPDE.createEM();
    try {
        em.getTransaction().begin();
        MedProducts myProduct = em.merge(product);

        myProduct.setText(txtName.getText().trim());
        myProduct.setSideEffects(txtSideEffects.getText().trim());
        myProduct.setACME(em.merge((ACME) cmbAcme.getSelectedItem()));

        for (TradeForm tf : myProduct.getTradeforms()) {
            em.lock(em.merge(tf), LockModeType.OPTIMISTIC_FORCE_INCREMENT);
            for (MedPackage mp : tf.getPackages()) {
                em.lock(em.merge(mp), LockModeType.OPTIMISTIC_FORCE_INCREMENT);
            }
        }

        em.lock(myProduct, LockModeType.OPTIMISTIC);

        em.getTransaction().commit();

        product = myProduct;
    } catch (Exception e) {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        OPDE.fatal(e);
    } finally {
        em.close();
    }
    dispose();

    //hier gehts weiter. prf auch die anderen locks bei den anderen editoren

}