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:com.intuit.tank.dao.ScriptDao.java

/**
 * // ww w . j a v  a  2 s .  com
 * @{inheritDoc
 */
@Override
public Script saveOrUpdate(Script script) {
    MethodTimer mt = new MethodTimer(LOG, getClass(), "saveOrUpdate").start();
    int size = script.getScriptSteps().size();
    ScriptUtil.setScriptStepLabels(script);
    // try {
    LOG.info("persisting script " + script.getName() + " with id " + script.getId() + " into database");
    try {
        EntityManager em = getEntityManager();
        getEmProvider().get().startTrasaction(this);
        SerializedScriptStep serializedScriptStep = serialize(script.getScriptSteps());
        serializedScriptStep
                .setSerialzedData(Hibernate.createBlob(serializedScriptStep.getBytes(), getHibernateSession()));
        SerializedScriptStep serializedSteps = new SerializedScriptStepDao().saveOrUpdate(serializedScriptStep);
        script.setSerializedScriptStepId(serializedScriptStep.getId());
        if (script.getId() == 0) {
            em.persist(script);
        } else {
            script = em.merge(script);
        }
        LOG.debug("Saved Script Steps with id " + serializedSteps.getId() + " for script " + script.getId());
        getEmProvider().get().commitTransaction(this);
    } finally {
        getEmProvider().get().cleanup(this);
    }
    mt.markAndLog("Store script with " + size + " steps to database.");
    mt.endAndLog();
    return script;
}

From source file:org.opencastproject.kernel.security.persistence.OrganizationDatabaseImpl.java

/**
 * @see org.opencastproject.kernel.security.persistence.OrganizationDatabase#storeOrganization(org.opencastproject.security.api.Organization)
 *///from w  ww .j a  v  a  2s .c o m
@Override
public void storeOrganization(Organization org) throws OrganizationDatabaseException {
    EntityManager em = null;
    EntityTransaction tx = null;
    try {
        em = emf.createEntityManager();
        tx = em.getTransaction();
        tx.begin();
        JpaOrganization organizationEntity = getOrganizationEntity(org.getId());
        if (organizationEntity == null) {
            JpaOrganization organization = new JpaOrganization(org.getId(), org.getName(), org.getServers(),
                    org.getAdminRole(), org.getAnonymousRole(), org.getProperties());
            em.persist(organization);
        } else {
            organizationEntity.setName(org.getName());
            organizationEntity.setAdminRole(org.getAdminRole());
            organizationEntity.setAnonymousRole(org.getAnonymousRole());
            organizationEntity.setServers(org.getServers());
            organizationEntity.setProperties(org.getProperties());
            em.merge(organizationEntity);
        }
        tx.commit();
    } catch (Exception e) {
        logger.error("Could not update organization: {}", e.getMessage());
        if (tx.isActive()) {
            tx.rollback();
        }
        throw new OrganizationDatabaseException(e);
    } finally {
        if (em != null)
            em.close();
    }
}

From source file:nl.b3p.kaartenbalie.core.server.monitoring.DataMonitoring.java

public void endClientRequest(String service, String operation, int bytesSentToUser, long totalResponseTime) {

    if (!isEnableMonitoring()) {
        return;//w w w. j ava 2 s . c o m
    }
    if (clientRequest == null) {
        return;
    }

    try {
        log.debug("Getting entity manager ......");
        EntityManager em = MyEMFDatabase.getEntityManager(MyEMFDatabase.MAIN_EM);

        requestOperation.setDuration(new Long(totalResponseTime));
        requestOperation.setBytesSentToUser(new Integer(bytesSentToUser));

        this.addRequestOperation(requestOperation);
        clientRequest.setService(service);
        clientRequest.setOperation(operation);
        clientRequest.setUser(user);
        clientRequest.setOrganization(organization);
        //Now Persist...
        Iterator iterRO = clientRequest.getRequestOperations().iterator();
        while (iterRO.hasNext()) {
            em.persist(iterRO.next());
        }
        Iterator iterSPR = clientRequest.getServiceProviderRequests().iterator();
        while (iterSPR.hasNext()) {
            em.persist(iterSPR.next());
        }
        em.persist(clientRequest);
        em.flush();
    } catch (Exception e) {
        log.error("Error logging request", e);
    }

    clientRequest = null;
}

From source file:com.adeptj.modules.data.jpa.core.AbstractJpaRepository.java

/**
 * {@inheritDoc}// w  w w. java2s.  co  m
 */
@Override
public <T extends BaseEntity> T insert(T entity) {
    EntityManager em = JpaUtil.createEntityManager(this.getEntityManagerFactory());
    try {
        em.getTransaction().begin();
        em.persist(entity);
        em.getTransaction().commit();
        return entity;
    } catch (Exception ex) { // NOSONAR
        Transactions.markRollback(em);
        throw new JpaException(ex);
    } finally {
        Transactions.rollback(em);
        JpaUtil.closeEntityManager(em);
    }
}

From source file:org.sigmah.server.endpoint.export.sigmah.handler.ProjectReportModelHandler.java

@Override
public void importModel(InputStream inputStream, EntityManager em, Authentication authentication)
        throws ExportException {
    ObjectInputStream objectInputStream;
    em.getTransaction().begin();/*  w  w  w .  j av a 2  s . co m*/
    try {
        objectInputStream = new ObjectInputStream(inputStream);
        ProjectReportModel projectReportModel = (ProjectReportModel) objectInputStream.readObject();
        projectReportModel.resetImport(modelesReset, modelesImport);
        saveProjectReportModelElement(projectReportModel, em);
        projectReportModel.setOrganization(authentication.getUser().getOrganization());
        em.persist(projectReportModel);
        em.getTransaction().commit();
    } catch (IOException e) {
        LOG.debug(e);
    } catch (ClassNotFoundException e) {
        LOG.debug(e);
    }
}

From source file:org.jasig.cas.ticket.registry.support.JpaLockingStrategy.java

private boolean acquire(final EntityManager em, Lock lock) {
    lock.setUniqueId(uniqueId);/*w ww.j ava2s . c om*/
    if (lockTimeout > 0) {
        final Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, lockTimeout);
        lock.setExpirationDate(cal.getTime());
    } else {
        lock.setExpirationDate(null);
    }
    boolean success = false;
    try {
        if (lock.getApplicationId() != null) {
            lock = em.merge(lock);
        } else {
            lock.setApplicationId(applicationId);
            em.persist(lock);
        }
        success = true;
    } catch (PersistenceException e) {
        success = false;
        if (logger.isDebugEnabled()) {
            logger.debug("{} could not obtain {} lock.", new Object[] { uniqueId, applicationId, e });
        } else {
            logger.info("{} could not obtain {} lock.", uniqueId, applicationId);
        }
    }
    return success;
}

From source file:org.apache.juddi.config.Install.java

private static void installTModels(EntityManager em, List<org.uddi.api_v3.TModel> apiTModelList,
        UddiEntityPublisher publisher, String nodeId) throws DispositionReportFaultMessage {
    if (apiTModelList != null) {
        for (org.uddi.api_v3.TModel apiTModel : apiTModelList) {
            String tModelKey = apiTModel.getTModelKey();

            if (tModelKey.toUpperCase().endsWith(KeyGenerator.KEYGENERATOR_SUFFIX.toUpperCase())) {
                installPublisherKeyGen(em, apiTModel, publisher, nodeId);
            } else {
                org.apache.juddi.model.Tmodel modelTModel = new org.apache.juddi.model.Tmodel();
                apiTModel.setTModelKey(apiTModel.getTModelKey().toLowerCase());

                MappingApiToModel.mapTModel(apiTModel, modelTModel);

                modelTModel.setAuthorizedName(publisher.getAuthorizedName());

                Date now = new Date();
                modelTModel.setCreated(now);
                modelTModel.setModified(now);
                modelTModel.setModifiedIncludingChildren(now);
                modelTModel.setNodeId(nodeId);

                em.persist(modelTModel);
            }//from   ww w. j a va  2  s  . co m

        }
    }

}

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

@Override
public ProposalBranch forkBranch(final ProposalBranch fork, final long branchToForkId) {
    Assert.notNull(fork, "No ProposalBag supplied !");
    Assert.isNull(fork.getId(), "Id should not be set for creation !");

    // Duplicate the branch to Fork
    new TxCallback(this.getEmf()) {

        @Override//from   w w w  .  ja v  a  2  s .c o m
        @SuppressWarnings("unchecked")
        protected void executeInTransaction(final EntityManager em) {
            final Query loadFullBranchQuery = em.createNamedQuery(ProposalBranch.LOAD_FULL_BRANCH);
            loadFullBranchQuery.setParameter("branchId", branchToForkId);
            final ProposalBranch branchToFork = Iterables.getFirst(loadFullBranchQuery.getResultList(), null);
            if (branchToFork == null) {
                throw new ProposalBranchNotFoundException();
            }

            fork.setBags(branchToFork.getBags());
            em.persist(fork);
        }
    };

    return fork;
}

From source file:com.medicaid.mmis.util.CodeMappingLoader.java

private static void importSheet(EntityManager em, SequenceGeneratorBean sequence, Workbook workbook,
        String sheetName) {/*from  w  w w.  ja v  a2 s  .c  om*/
    logger.info("Importing legacy mapping from worksheet: " + sheetName);
    Sheet sheet = workbook.getSheet(sheetName);
    Iterator<Row> rowIterator = sheet.rowIterator();
    int total = 0;
    while (rowIterator.hasNext()) {
        Row row = (Row) rowIterator.next();
        if (row.getRowNum() < 1) {
            continue;
        }

        Cell systemIdCell = row.getCell(0);
        Cell codeTypeCell = row.getCell(1);
        Cell internalCodeCell = row.getCell(2);
        Cell externalCodeCell = row.getCell(4);
        if (systemIdCell == null || StringUtils.isBlank(systemIdCell.getStringCellValue())) {
            continue;
        }
        if (codeTypeCell == null || StringUtils.isBlank(codeTypeCell.getStringCellValue())) {
            continue;
        }
        if (internalCodeCell == null || StringUtils.isBlank(internalCodeCell.getStringCellValue())) {
            continue;
        }
        if (externalCodeCell == null || StringUtils.isBlank(externalCodeCell.getStringCellValue())) {
            continue;
        }

        LegacySystemMapping mapping = new LegacySystemMapping();
        mapping.setId(sequence.getNextValue("LEGACY_MAPPING"));
        mapping.setSystemName(systemIdCell.getStringCellValue());
        mapping.setExternalCode(externalCodeCell.getStringCellValue());
        mapping.setInternalCode(internalCodeCell.getStringCellValue());
        mapping.setCodeType(codeTypeCell.getStringCellValue());
        logger.debug("Inserting mapping: " + mapping);
        em.persist(mapping);
        total++;
    }
    logger.info("Total records imported from sheet: " + total);
    System.out.println("Total records imported from sheet[" + sheetName + "] : " + total);
}

From source file:net.officefloor.tutorial.transactionhttpserver.TransactionHttpServerTest.java

/**
 * Ensure the JPA connects to database./*from www.j  av  a 2 s.  c o  m*/
 */
public void testJpa() throws Exception {

    // Request page to allow time for database setup
    this.doRequest("http://localhost:7878/users.woof");

    // Obtain entity manager
    EntityManagerFactory factory = Persistence.createEntityManagerFactory("example");
    EntityManager manager = factory.createEntityManager();

    // Ensure can obtain user and person
    Query query = manager.createQuery("SELECT U FROM User U");
    User user = (User) query.getSingleResult();
    assertEquals("Incorrect user name", "daniel", user.getUserName());
    Person person = user.getPerson();
    assertEquals("Incorrect person name", "Daniel Sagenschneider", person.getFullName());

    // Ensure persist user and person
    User newUser = new User();
    newUser.setUserName("test");
    Person newPerson = new Person();
    newPerson.setFullName("TEST");
    newPerson.setUser(newUser);
    manager.persist(newPerson);
    manager.close();

    // Ensure user and person persisted
    manager = factory.createEntityManager();
    User retrievedUser = manager.find(User.class, newUser.getId());
    assertEquals("Incorrect retrieved user name", "test", retrievedUser.getUserName());
    Person retrievedPerson = retrievedUser.getPerson();
    assertEquals("Incorrect retrieved full name", "TEST", retrievedPerson.getFullName());

    // Close persistence
    factory.close();
}