List of usage examples for javax.persistence EntityManager merge
public <T> T merge(T entity);
From source file:org.eclipse.smila.binarystorage.persistence.jpa.JPABinaryPersistence.java
/** * Stores the given BinaryStorageDao, updating an existing one or creating a new one. * * @param dao/*from w w w .java 2s . co m*/ * the BinaryStorageDao to store * @throws BinaryStorageException * if any error occurs */ // TODO: don't know if this synchronize is good, was needed to pass the JUNit test TestConcurrentBSSAccessJPA private synchronized void store(final BinaryStorageDao dao) throws BinaryStorageException { _lock.readLock().lock(); try { final EntityManager em = createEntityManager(); final EntityTransaction transaction = em.getTransaction(); try { transaction.begin(); if (findBinaryStorageDao(em, dao.getId()) == null) { em.persist(dao); } else { em.merge(dao); } transaction.commit(); if (_log.isTraceEnabled()) { _log.trace("stored content of id:" + dao.getId()); } } catch (final Exception e) { if (transaction.isActive()) { transaction.rollback(); } throw new BinaryStorageException(e, "error storing record id: " + dao.getId()); } finally { closeEntityManager(em); } } finally { _lock.readLock().unlock(); } }
From source file:org.nuxeo.theme.webwidgets.providers.PersistentProvider.java
public synchronized void reorderWidgets(final List<Widget> widgets) throws ProviderException { try {//from w w w.j a v a2 s. com getPersistenceProvider().run(true, new RunVoid() { public void runWith(EntityManager em) { int i = 0; for (Widget w : widgets) { WidgetEntity widget = ((WidgetEntity) w); int order = widget.getOrder(); if (order != i) { ((WidgetEntity) w).setOrder(i); em.merge(w); } i = i + 1; } } }); } catch (ClientException e) { throw new ProviderException(e); } }
From source file:com.busimu.core.dao.impl.UserMngDaoPolicyJpaImpl.java
/** * {@inheritDoc}/*from www . jav a 2 s . c o m*/ */ @Override public User activateUser(User user, String licenseCode) { EntityManager em = ((EntityManagerHolder) TransactionSynchronizationManager.getResource(emf)) .getEntityManager(); EntityTransaction tx = em.getTransaction(); License l = getLicenseByCode(em, licenseCode); if (l != null) { if (!tx.isActive()) { tx.begin(); } user.setType(User.Type.valueOf(l.getType().name())); user.setStatus(User.Status.ACTIVE); user = em.merge(user); em.remove(l); tx.commit(); } return user; }
From source file:fr.mby.opa.picsimpl.dao.DbAlbumDao.java
@Override public Album updateAlbum(final Album album) throws AlbumNotFoundException { Assert.notNull(album, "No Album supplied !"); Assert.notNull(album.getId(), "Id should be set for update !"); final TxCallbackReturn<Album> txCallback = new TxCallbackReturn<Album>(this.getEmf()) { @Override//from w w w .j a v a 2 s .c o m protected Album executeInTransaction(final EntityManager em) { final Album managedAlbum = em.find(Album.class, album.getId(), LockModeType.WRITE); if (managedAlbum == null) { throw new AlbumNotFoundException(); } Album updatedAlbum = null; if (!managedAlbum.getLocked()) { // Update album if not locked ! managedAlbum.setName(album.getName()); managedAlbum.setDescription(album.getDescription()); updatedAlbum = em.merge(managedAlbum); } return updatedAlbum; } }; return txCallback.getReturnedValue(); }
From source file:in.bookmylab.jpa.JpaDAO.java
public User saveUser(User user, boolean savePassword) { EntityManager em = emf.createEntityManager(); try {/*from w ww.j a va 2 s .c om*/ user.password = Utils.hashPassword(user.password); em.getTransaction().begin(); if (user.userId == null) { grantDefaultRoleToUser(em, user); em.persist(user); } else { user = em.merge(user); if (savePassword) { Query q = em.createNamedQuery("User.setPassword"); q.setParameter("password", user.password); q.setParameter("userId", user.userId); q.executeUpdate(); } } em.getTransaction().commit(); } finally { em.clear(); em.close(); } return user; }
From source file:org.nuxeo.ecm.activity.ActivityStreamServiceImpl.java
protected void updateActivity(final Activity activity) { try {//from ww w.ja va2 s . co m getOrCreatePersistenceProvider().run(false, new PersistenceProvider.RunCallback<Activity>() { @Override public Activity runWith(EntityManager em) { activity.setLastUpdatedDate(new Date()); return em.merge(activity); } }); } catch (ClientException e) { throw new ClientRuntimeException(e); } }
From source file:org.eclipse.smila.recordstorage.impl.RecordStorageImpl.java
/** * {@inheritDoc}/*from w ww .j av a 2 s.co m*/ */ @Override public void storeRecord(final Record record) throws RecordStorageException { if (record == null) { throw new RecordStorageException("parameter record is null"); } _lock.readLock().lock(); try { final EntityManager em = createEntityManager(); final EntityTransaction transaction = em.getTransaction(); try { final RecordDao dao = new RecordDao(record); transaction.begin(); if (findRecordDao(em, record.getId()) == null) { em.persist(dao); } else { em.merge(dao); } transaction.commit(); if (_log.isTraceEnabled()) { _log.trace("stored record Id:" + record.getId()); } } catch (final Exception e) { if (transaction.isActive()) { transaction.rollback(); } throw new RecordStorageException(e, "error storing record id: " + record.getId()); } finally { closeEntityManager(em); } } finally { _lock.readLock().unlock(); } }
From source file:org.sigmah.server.endpoint.gwtrpc.PasswordManagementServlet.java
@Override @Transactional//from w w w .j av a2 s .c o m public void forgotPassword(String email, String language, String hostUrl) throws Exception { final EntityManager entityManager = injector.getInstance(EntityManager.class); // find user final Query query = entityManager.createQuery("SELECT u FROM User u WHERE u.email = :email"); query.setParameter("email", email); final User user = (User) query.getSingleResult(); // unique key is stored and sent by email String uniqueKey = UUID.randomUUID().toString(); uniqueKey = uniqueKey.replaceAll("-", ""); //squeeze // store key and date user.setChangePasswordKey(uniqueKey); user.setDateChangePasswordKeyIssued(new Date()); entityManager.merge(user); // build a link to pass by email, so the user can reset the password following the link final StringBuilder linkBuilder = new StringBuilder(hostUrl); linkBuilder.append("?token=" + URLEncoder.encode(uniqueKey, "UTF-8")); linkBuilder.append("&locale=" + language); linkBuilder.append("#passwordReset"); // send email final SimpleEmail mail = new SimpleEmail(); final Locale locale = getLocale(language); final ResourceBundle bundle = ResourceBundle.getBundle("org.sigmah.server.mail.MailMessages", locale); mail.setSubject(bundle.getString("resetPassword.subject")); mail.setMsg(MessageFormat.format(bundle.getString("resetPassword.content"), linkBuilder.toString())); mail.addTo(email, User.getUserCompleteName(user)); final MailSender mailSender = injector.getInstance(MailSender.class); mailSender.send(mail); log.info(String.format("Password reset email has been sent to '%s' with a link [%s]", email, linkBuilder.toString())); }
From source file:edu.vt.middleware.gator.JpaConfigManager.java
/** {@inheritDoc}. */ @Transactional(propagation = Propagation.REQUIRED) public void savePermissions(final ProjectConfig project, final String sid, final int bits) { final EntityManager em = getEntityManager(); if (logger.isDebugEnabled()) { logger.debug(String.format("Setting permissions for %s to %s on %s.", sid, bits, project)); }// ww w . j a v a 2 s . c om final PermissionConfig perm = project.getPermission(sid); if (perm == null) { project.addPermission(new PermissionConfig(sid, bits)); } else { perm.setPermissionBits(bits); } project.setModifiedDate(Calendar.getInstance()); em.merge(project); }