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:net.sf.ehcache.openjpa.datacache.TestEhCache.java

@Test
public void testClearCache() {
    EntityManagerFactory emf = em.getEntityManagerFactory();

    EntityManager entityManager = emf.createEntityManager();
    EntityTransaction tx = entityManager.getTransaction();
    tx.begin();/*from  w  w w  .  j av a2  s.c  o m*/
    SubQObject subQObject = new SubQObject("one", "two");
    QObject qObject = new QObject("one");
    PObject pObject = new PObject("one");
    entityManager.persist(subQObject);
    entityManager.persist(qObject);
    entityManager.persist(pObject);
    tx.commit();
    assertTrue(getCache(subQObject.getClass()).contains(getOpenJPAId(subQObject, subQObject.getId())));
    assertTrue(getCache(qObject.getClass()).contains(getOpenJPAId(qObject, qObject.getId())));
    assertTrue(getCache(pObject.getClass()).contains(getOpenJPAId(pObject, pObject.getId())));
    evictAllOfType(qObject.getClass(), false);
    assertFalse("QObject entries should be all gone",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(qObject.getClass(), qObject.getId()));
    assertTrue("SubQObject entries should still be in the cache",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(subQObject.getClass(), subQObject.getId()));
    assertTrue("This PObject object should still be in the cache",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(pObject.getClass(), pObject.getId()));
    tx = entityManager.getTransaction();
    tx.begin();
    qObject = new QObject("two");
    entityManager.persist(qObject);
    tx.commit();
    evictAllOfType(qObject.getClass(), true);
    assertFalse("QObject entries should be all gone",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(qObject.getClass(), qObject.getId()));
    assertFalse("SubQObject entries should be all gone",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(subQObject.getClass(), subQObject.getId()));
    assertTrue("This PObject object should still be in the cache",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(pObject.getClass(), pObject.getId()));
    tx = entityManager.getTransaction();
    tx.begin();
    qObject = new QObject("three");
    entityManager.persist(qObject);
    subQObject = new SubQObject("two", "two");
    entityManager.persist(subQObject);
    tx.commit();
    evictAllOfType(subQObject.getClass(), false);
    assertTrue("QObject entries should still be in the cache",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(qObject.getClass(), qObject.getId()));
    assertFalse("SubQObject entries should be all gone",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(subQObject.getClass(), subQObject.getId()));
    assertTrue("This PObject object should still be in the cache",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(pObject.getClass(), pObject.getId()));
    tx = entityManager.getTransaction();
    tx.begin();
    subQObject = new SubQObject("three", "three");
    entityManager.persist(subQObject);
    tx.commit();
    evictAllOfType(pObject.getClass(), true);
    assertTrue("QObject entries should still be in the cache",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(qObject.getClass(), qObject.getId()));
    assertTrue("SubQObject entries should still be in the cache",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(subQObject.getClass(), subQObject.getId()));
    assertFalse("This PObject object should be gone",
            OpenJPAPersistence.cast(emf).getStoreCache().contains(pObject.getClass(), pObject.getId()));
}

From source file:org.apache.openjpa.persistence.xmlmapping.query.TestXMLCustomerOrder.java

private void persistEntities(EntityManager em) {
    Customer c2 = new Customer();
    c2.setCid(new Customer.CustomerKey("USA", 2));
    c2.setName("A&J Auto");
    c2.setRating(CreditRating.GOOD);/*from w ww . jav a2 s  .  c o  m*/
    c2.setAddress(new EAddress("2480 Campbell Ave", "Campbell", "CA", "95123"));
    em.persist(c2);

    Customer c1 = new Customer();
    c1.setCid(new Customer.CustomerKey("USA", 1));
    c1.setName("Harry's Auto");
    c1.setRating(CreditRating.GOOD);
    c1.setAddress(new EAddress("12500 Monterey", "San Jose", "CA", "95141"));
    em.persist(c1);

    Order o1 = new Order(ORDER_1_OID, ORDER_1_AMOUNT, ORDER_1_DELIVERED, c1);
    o1.setShipAddress(createUSAAddress(c1.getName()));
    em.persist(o1);

    Order o2 = new Order(ORDER_2_OID, ORDER_2_AMOUNT, ORDER_2_DELIVERED, c1);
    o2.setShipAddress(createCANAddress(c2.getName()));
    em.persist(o2);
}

From source file:org.opencastproject.messages.MailService.java

public static EmailConfigurationDto mergeEmailConfiguration(EmailConfiguration config, String organization,
        EntityManager em) {
    Option<EmailConfigurationDto> configOption = findEmailConfiguration(organization, em);
    EmailConfigurationDto dto;/*from  ww w .ja  va 2  s.  c  om*/
    if (configOption.isSome()) {
        dto = configOption.get();
        dto.setTransport(config.getTransport());
        dto.setPassword(config.getPassword());
        dto.setPort(config.getPort());
        dto.setServer(config.getServer());
        dto.setSsl(config.isSsl());
        dto.setUserName(config.getUserName());
        em.merge(dto);
    } else {
        dto = new EmailConfigurationDto(organization, config.getTransport(), config.getServer(),
                config.getPort(), config.getUserName(), config.getPassword(), config.isSsl());
        em.persist(dto);
    }
    return dto;
}

From source file:org.openhab.persistence.jpa.internal.JpaPersistenceService.java

@Override
public void store(Item item, String alias) {
    logger.debug("Storing item: " + item.getName());

    if (item.getState() instanceof UnDefType) {
        logger.debug("This item is of undefined type. Cannot persist it!");
        return;/*from ww w.j  av a  2 s. co m*/
    }

    if (!JpaConfiguration.isInitialized) {
        logger.warn("Trying to create EntityManagerFactory but we don't have configuration yet!");
        return;
    }

    // determine item name to be stored
    String name = (alias != null) ? alias : item.getName();

    JpaPersistentItem pItem = new JpaPersistentItem();
    try {
        String newValue = StateHelper.toString(item.getState());
        pItem.setValue(newValue);
        logger.debug("Stored new value: {}", newValue);
    } catch (Exception e1) {
        logger.error("Error on converting state value to string: {}", e1.getMessage());
        return;
    }
    pItem.setName(name);
    pItem.setRealName(item.getName());
    pItem.setTimestamp(new Date());

    EntityManager em = getEntityManagerFactory().createEntityManager();
    try {
        logger.debug("Persisting item...");
        // In RESOURCE_LOCAL calls to EntityManager require a begin/commit         
        em.getTransaction().begin();
        em.persist(pItem);
        em.getTransaction().commit();
        logger.debug("Persisting item...done");
    } catch (Exception e) {
        logger.error("Error on persisting item! Rolling back!");
        logger.error(e.getMessage(), e);
        em.getTransaction().rollback();
    } finally {
        em.close();
    }

    logger.debug("Storing item...done");
}

From source file:org.apache.falcon.jdbc.MonitoringJdbcStateStore.java

public void putPendingInstances(String feed, String clusterName, Date nominalTime) {
    EntityManager entityManager = getEntityManager();
    PendingInstanceBean pendingInstanceBean = new PendingInstanceBean();
    pendingInstanceBean.setFeedName(feed);
    pendingInstanceBean.setClusterName(clusterName);
    pendingInstanceBean.setNominalTime(nominalTime);

    beginTransaction(entityManager);/*from   w  w w  . j  a  v  a  2  s.  c o  m*/
    entityManager.persist(pendingInstanceBean);
    commitAndCloseTransaction(entityManager);
}

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

public void saveProfile(UserProfile profile) {
    EntityManager em = emf.createEntityManager();
    try {//from www . j  a va 2s.co m
        em.getTransaction().begin();
        if (profile.profileId == null) {
            em.persist(profile);
        } else {
            em.merge(profile);
        }
        em.getTransaction().commit();
    } finally {
        em.close();
    }
}

From source file:it.infn.ct.futuregateway.apiserver.v1.TaskCollectionService.java

/**
 * Register a new task./* w w w.j  a v  a2  s . c  o  m*/
 *
 * @param task The task to register
 * @return The task registered
 */
@POST
@Status(Response.Status.CREATED)
@Consumes({ MediaType.APPLICATION_JSON, Constants.INDIGOMIMETYPE })
@Produces(Constants.INDIGOMIMETYPE)
public final Task createTask(final Task task) {
    if (task.getApplicationId() == null) {
        throw new BadRequestException("A valid application for the task" + " must be provided");
    }
    task.addObserver(new TaskObserver(getEntityManagerFactory(), getSubmissionThreadPool()));
    task.setDateCreated(new Date());
    task.setUserName(getUser());
    task.setStatus(Task.STATUS.WAITING);
    EntityManager em = getEntityManager();
    EntityTransaction et = null;
    try {
        et = em.getTransaction();
        et.begin();
        Application app = em.find(Application.class, task.getApplicationId());
        if (app == null) {
            throw new BadRequestException("Application id not valid");
        }
        task.setApplicationDetail(app);
        em.persist(task);
        et.commit();
        log.debug("New task registered: " + task.getId());
    } catch (BadRequestException bre) {
        throw bre;
    } catch (RuntimeException re) {
        log.error("Impossible to create a task");
        log.debug(re);
        throw re;
    } finally {
        if (et != null && et.isActive()) {
            et.rollback();
        }
        em.close();
    }
    return task;
}

From source file:org.apache.falcon.state.store.jdbc.JDBCStateStore.java

@Override
public void putEntity(EntityState entityState) throws StateStoreException {
    EntityID entityID = new EntityID(entityState.getEntity());
    String key = entityID.getKey();
    if (entityExists(entityID)) {
        throw new StateStoreException("Entity with key, " + key + " already exists.");
    }/*from   ww  w.  ja  v a  2s  .co m*/
    EntityBean entityBean = null;
    try {
        entityBean = BeanMapperUtil.convertToEntityBean(entityState);
        EntityManager entityManager = getEntityManager();
        beginTransaction(entityManager);
        entityManager.persist(entityBean);
        commitAndCloseTransaction(entityManager);
    } catch (IOException e) {
        throw new StateStoreException(e);
    }
}

From source file:org.apache.falcon.state.store.jdbc.JDBCStateStore.java

@Override
public void putExecutionInstance(InstanceState instanceState) throws StateStoreException {
    InstanceID instanceID = new InstanceID(instanceState.getInstance());
    if (executionInstanceExists(instanceID)) {
        throw new StateStoreException("Instance with key, " + instanceID + " already exists.");
    }/*from ww w  .j  a  v  a 2 s  .com*/
    try {
        InstanceBean instanceBean = BeanMapperUtil.convertToInstanceBean(instanceState);
        EntityBean entityBean = getEntityBean(new InstanceID(instanceState.getInstance()).getEntityID());
        instanceBean.setEntityBean(entityBean);
        EntityManager entityManager = getEntityManager();
        beginTransaction(entityManager);
        entityManager.persist(instanceBean);
        commitAndCloseTransaction(entityManager);
    } catch (IOException e) {
        throw new StateStoreException(e);
    }
}

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

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

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