Example usage for javax.persistence EntityManager persist

List of usage examples for javax.persistence EntityManager persist

Introduction

In this page you can find the example usage for javax.persistence EntityManager persist.

Prototype

public void persist(Object entity);

Source Link

Document

Make an instance managed and persistent.

Usage

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

public void saveXrdBooking(XrdLabBooking xrd) throws AppException {
    EntityManager em = emf.createEntityManager();
    try {// w  w  w  .ja  v  a 2 s .  c  om
        em.getTransaction().begin();
        if (xrd.xrdId == null) {
            em.persist(xrd);
            fixAnalysisModesAndResourceType(xrd.booking, em, false);
        } else {
            // Validate status change, if any
            Query q = em.createNamedQuery("ResourceBooking.findById");
            ResourceBooking rb = (ResourceBooking) q.setParameter("bookingId", xrd.booking.bookingId)
                    .getSingleResult();
            if (!statusChangeValid(rb.status, xrd.booking.status)) {
                throw new AppException(String.format("Status cannot be changed from %s to %s.", rb.status,
                        xrd.booking.status));
            }

            fixAnalysisModesAndResourceType(xrd.booking, em, true);
            em.merge(xrd);
        }
        em.getTransaction().commit();
    } finally {
        em.close();
    }
}

From source file:uk.ac.edukapp.service.UserAccountService.java

public Useraccount updateUser(int userId, String username, String email, String password, String realname) {

    Useraccount user = this.getUserAccount(userId);
    EntityManager em = getEntityManagerFactory().createEntityManager();
    em.getTransaction().begin();//from   www .j a va 2s  . co  m
    user.setEmail(email);

    UUID token = UUID.randomUUID();
    String salt = token.toString();
    String hashedPassword = MD5Util.md5Hex(salt + password);
    user.setPassword(hashedPassword);
    user.setSalt(salt);
    em.persist(user);

    user.setUsername(username);

    Accountinfo info = user.getAccountInfo();
    info.setRealname(realname);
    em.persist(user);
    em.persist(info);

    em.getTransaction().commit();
    em.close();

    return user;
}

From source file:org.eclipse.skalli.core.storage.jpa.JPAStorageComponent.java

@Override
public void archive(String category, String id) throws StorageException {
    EntityManager em = getEntityManager();

    try {/*  ww w  .  j  ava 2  s. c  o  m*/
        em.getTransaction().begin();

        // find original StorageItem
        StorageItem item = findStorageItem(category, id, em);
        if (item == null) {
            // nothing to archive
            return;
        }

        // write to HistoryStorage
        HistoryStorageItem histItem = new HistoryStorageItem(item);
        em.persist(histItem);
        em.getTransaction().commit();
    } catch (Exception e) {
        throw new StorageException("Failed to archive data", e);
    } finally {
        em.close();
    }
}

From source file:org.apache.camel.component.jpa.JpaWithNamedQueryTest.java

@Test
public void testProducerInsertsIntoDatabaseThenConsumerFiresMessageExchange() throws Exception {
    transactionStrategy.execute(new JpaCallback() {
        public Object doInJpa(EntityManager entityManager) throws PersistenceException {
            // lets delete any exiting records before the test
            entityManager.createQuery("delete from " + entityName).executeUpdate();

            // now lets create a dummy entry
            MultiSteps dummy = new MultiSteps("cheese");
            dummy.setStep(4);//w w w.  j av  a2 s. co m
            entityManager.persist(dummy);
            return null;
        }
    });

    List results = jpaTemplate.find(queryText);
    assertEquals("Should have no results: " + results, 0, results.size());

    // lets produce some objects
    template.send(endpoint, new Processor() {
        public void process(Exchange exchange) {
            exchange.getIn().setBody(new MultiSteps("foo@bar.com"));
        }
    });

    // now lets assert that there is a result
    results = jpaTemplate.find(queryText);
    assertEquals("Should have results: " + results, 1, results.size());
    MultiSteps mail = (MultiSteps) results.get(0);
    assertEquals("address property", "foo@bar.com", mail.getAddress());

    // now lets create a consumer to consume it
    consumer = endpoint.createConsumer(new Processor() {
        public void process(Exchange e) {
            LOG.info("Received exchange: " + e.getIn());
            receivedExchange = e;
            latch.countDown();
        }
    });
    consumer.start();

    boolean received = latch.await(50, TimeUnit.SECONDS);
    assertTrue("Did not receive the message!", received);

    assertReceivedResult(receivedExchange);

    // lets now test that the database is updated
    // we need to sleep as we will be invoked from inside the transaction!
    Thread.sleep(1000);

    transactionStrategy.execute(new JpaCallback() {
        @SuppressWarnings("unchecked")
        public Object doInJpa(EntityManager entityManager) throws PersistenceException {

            // now lets assert that there are still 2 entities left
            List<MultiSteps> rows = entityManager.createQuery("select x from MultiSteps x").getResultList();
            assertEquals("Number of entities: " + rows, 2, rows.size());

            int counter = 1;
            for (MultiSteps row : rows) {
                LOG.info("entity: " + counter++ + " = " + row);

                if (row.getAddress().equals("foo@bar.com")) {
                    LOG.info("Found updated row: " + row);

                    assertEquals("Updated row step for: " + row, getUpdatedStepValue(), row.getStep());
                } else {
                    // dummy row
                    assertEquals("dummy row step for: " + row, 4, row.getStep());
                }
            }
            return null;
        }
    });

    JpaConsumer jpaConsumer = (JpaConsumer) consumer;
    assertURIQueryOption(jpaConsumer);
}

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

@Override
@Transactional// w w  w  . j a v a 2  s.com
public SessionImpl createSession(BlackboardSessionResponse sessionResponse, String guestUrl) {
    //Find the creator user
    final String creatorId = sessionResponse.getCreatorId();
    ConferenceUserImpl creator = this.conferenceUserDao.getUserByUniqueId(creatorId);
    if (creator == null) {
        //This should be pretty rare as the creator should be the currently authd user
        logger.warn(
                "Internal user for session creator {} doesn't exist for session {}. Creating a bare bones user to compensate",
                creatorId, sessionResponse.getSessionId());
        creator = this.conferenceUserDao.createInternalUser(creatorId);
    }

    //Create and populate a new blackboardSession
    final SessionImpl session = new SessionImpl(sessionResponse.getSessionId(), creator);

    updateBlackboardSession(sessionResponse, session);

    session.setGuestUrl(guestUrl);

    //Persist and return the new session
    final EntityManager entityManager = this.getEntityManager();
    entityManager.persist(session);

    creator.getOwnedSessions().add(session);
    entityManager.persist(creator);

    return session;
}

From source file:org.opencastproject.userdirectory.jpa.JpaUserAndRoleProvider.java

/**
 * A utility class to load the user directory.
 * /*from   ww  w. j  a  v a 2 s .  c o  m*/
 * @param user
 *          the user object
 */
public void addUser(JpaUser user) {

    // Create a JPA user with an encoded password.
    String encodedPassword = PasswordEncoder.encode(user.getPassword(), user.getUsername());
    user = new JpaUser(user.getUsername(), encodedPassword, user.getOrganization(), user.getRoles());

    // Then save the user
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        em.persist(user);
        tx.commit();
    } finally {
        if (tx.isActive()) {
            tx.rollback();
        }
        if (em != null)
            em.close();
    }
}

From source file:org.ejbca.extra.db.MessageHome.java

/**
 * Creates a message and store it to database with status waiting.
 * If a message already exists, it will be overwritten.
 * // w  w  w. ja  va  2s.  c  om
 * @param messageId, the unique message id.
 * @param message, the actual message string.
 * @return String, the uniqueId that is the primary key in the database
 */

public String create(String messageId, SubMessages submessages) {
    log.trace(">create : Message, messageId : " + messageId);
    EntityManager entityManager = getNewEntityManager();
    Message message;
    try {
        message = Message.findByUniqueId(entityManager, Message.createUniqueIdString(messageId, type));
        if (message != null) {
            message.update(submessages, Message.STATUS_WAITING);
        } else {
            message = new Message(messageId, type);
            message.setSubMessages(submessages);
            entityManager.persist(message);
        }
    } finally {
        closeEntityManager(entityManager);
    }
    log.trace("<create : Message, messageid : " + messageId);
    return message.getUniqueId();
}

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

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

    final EntityManager entityManager = this.getEntityManager();

    final PresentationImpl presentationImpl = entityManager.find(PresentationImpl.class,
            presentation.getPresentationId());

    final ConferenceUser creator = presentationImpl.getCreator();
    final ConferenceUserImpl creatorImpl = this.conferenceUserDao.getUser(creator.getUserId());
    creatorImpl.getPresentations().remove(presentationImpl);

    entityManager.remove(presentationImpl);
    entityManager.persist(creatorImpl);
}

From source file:org.eclipse.skalli.core.storage.jpa.JPAStorageComponent.java

@Override
public void write(String category, String id, InputStream blob) throws StorageException {
    EntityManager em = getEntityManager();

    em.getTransaction().begin();//  w ww.  java2 s.  c  om
    try {
        StorageItem item = findStorageItem(category, id, em);
        if (item == null) {
            StorageItem newItem = new StorageItem();
            newItem.setId(id);
            newItem.setCategory(category);
            newItem.setDateModified(new Date());
            newItem.setContent(IOUtils.toString(blob, "UTF-8"));
            em.persist(newItem);
        } else { //update
            item.setDateModified(new Date());
            item.setContent(IOUtils.toString(blob, "UTF-8"));
        }
        em.getTransaction().commit();
    } catch (Exception e) {
        throw new StorageException("Failed to write data", e);
    } finally {
        em.close();
    }
}

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
 *
 */// www.j av  a 2 s.  c o  m
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);

}