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:org.apache.openjpa.jdbc.meta.strats.AbstractLobTest.java

public void testSetFlushAndReset() throws IOException {
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();//from www .ja v  a  2  s  .co  m
    LobEntity le = newLobEntity(createLobData(), 1);
    em.persist(le);
    em.flush();
    String string = createLobData2();
    changeStream(le, string);
    LobEntity entity = (LobEntity) em.find(getLobEntityClass(), 1);
    assertEquals(string, getStreamContentAsString(entity.getStream()));
    em.getTransaction().commit();
    em.close();
}

From source file:org.apache.openjpa.jdbc.meta.strats.AbstractLobTest.java

public void testSetResetAndFlush() throws IOException {
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();// w ww . ja  va2  s .c om
    LobEntity le = newLobEntity(createLobData(), 1);
    em.persist(le);
    String string = createLobData2();
    changeStream(le, string);
    em.flush();
    em.getTransaction().commit();
    em.close();
    em = emf.createEntityManager();
    em.getTransaction().begin();
    LobEntity entity = (LobEntity) em.find(getLobEntityClass(), 1);
    assertEquals(string, getStreamContentAsString(entity.getStream()));
    em.getTransaction().commit();
    em.close();
}

From source file:org.rhq.enterprise.server.drift.JPADriftServerBeanTest.java

public void persistResourceChangeSet() {
    // first create and persist the drift definition
    final DriftDefinition driftDef = new DriftDefinition(new Configuration());
    driftDef.setName("test::persistResourceChangeSet");
    driftDef.setEnabled(true);/*from  w ww.  ja  v  a 2  s  .c o  m*/
    driftDef.setDriftHandlingMode(normal);
    driftDef.setInterval(2400L);
    driftDef.setBasedir(new DriftDefinition.BaseDirectory(fileSystem, "/foo/bar/test"));
    driftDef.setResource(resource);

    executeInTransaction(new TransactionCallback() {
        @Override
        public void execute() throws Exception {
            EntityManager em = getEntityManager();
            em.persist(driftDef);
        }
    });

    // create the change set to be persisted
    DriftChangeSetDTO changeSet = new DriftChangeSetDTO();
    changeSet.setCategory(COVERAGE);
    changeSet.setVersion(1);
    changeSet.setDriftDefinitionId(driftDef.getId());
    changeSet.setResourceId(resource.getId());
    changeSet.setDriftHandlingMode(normal);
    changeSet.setCtime(System.currentTimeMillis());

    DriftDTO drift1 = new DriftDTO();
    drift1.setCategory(FILE_ADDED);
    drift1.setPath("drift.1");
    drift1.setChangeSet(changeSet);
    drift1.setCtime(System.currentTimeMillis());
    drift1.setNewDriftFile(toDTo(driftFile1));

    DriftDTO drift2 = new DriftDTO();
    drift2.setCategory(FILE_ADDED);
    drift2.setPath("drift.2");
    drift2.setChangeSet(changeSet);
    drift2.setCtime(System.currentTimeMillis());
    drift2.setNewDriftFile(toDTo(driftFile2));

    Set<DriftDTO> drifts = new HashSet<DriftDTO>();
    drifts.add(drift1);
    drifts.add(drift2);
    changeSet.setDrifts(drifts);

    String newChangeSetId = jpaDriftServer.persistChangeSet(getOverlord(), changeSet);

    // verify that the change set was persisted
    JPADriftChangeSetCriteria criteria = new JPADriftChangeSetCriteria();
    criteria.addFilterId(newChangeSetId);
    criteria.fetchDrifts(true);

    PageList<JPADriftChangeSet> changeSets = jpaDriftServer.findDriftChangeSetsByCriteria(getOverlord(),
            criteria);
    assertEquals("Expected to find one change set", 1, changeSets.size());

    JPADriftChangeSet jpaChangeSet = changeSets.get(0);
    assertEquals(
            "Expected change set to contain two drifts. This could be a result of the change set not being "
                    + "persisted correctly or the criteria fetch being done incorrectly.",
            2, jpaChangeSet.getDrifts().size());

    AssertUtils.assertPropertiesMatch("The change set was not persisted correctly", changeSet, jpaChangeSet,
            "id", "drifts", "class", "ctime");

    List<? extends Drift> expectedDrifts = asList(drift1, drift2);
    List<? extends Drift> actualDrifts = new ArrayList(jpaChangeSet.getDrifts());

    // We ignore the id and ctime properties because those are set by JPADriftServerBean
    // and are somewhat implmentation specific. We ignore the directory property because
    // it is really a calculated property. newDriftFile has to be compared separately
    // since it does not implement equals.
    AssertUtils.assertCollectionMatchesNoOrder("The change set drifts were not persisted correctly",
            (List<Drift>) expectedDrifts, (List<Drift>) actualDrifts, "id", "ctime", "changeSet", "directory",
            "newDriftFile", "class");

    assertPropertiesMatch("The newDriftFile property was not set correctly for " + drift1,
            drift1.getNewDriftFile(), findDriftByPath(actualDrifts, "drift.1").getNewDriftFile(), "class",
            "ctime");
    assertPropertiesMatch("The newDriftFile property was not set correctly for " + drift2,
            drift2.getNewDriftFile(), findDriftByPath(actualDrifts, "drift.2").getNewDriftFile(), "class",
            "ctime");
}

From source file:com.nokia.helium.metadata.tests.TestORMFMPPLoader.java

/**
 * Populates the LogFile table with basic data.
 * @throws MetadataException//from w  w  w  .ja  v a 2s. c  o m
 * @throws IOException
 */
@Before
public void populateDatabase() throws MetadataException, IOException {
    File tempdir = new File(System.getProperty("test.temp.dir"));
    tempdir.mkdirs();
    database = new File(tempdir, "test_db");
    if (database.exists()) {
        FileUtils.forceDelete(database);
    }
    EntityManagerFactory factory = FactoryManager.getFactoryManager().getEntityManagerFactory(database);
    EntityManager em = factory.createEntityManager();
    try {
        em.getTransaction().begin();
        for (int i = 0; i < 2000; i++) {
            LogFile lf = new LogFile();
            lf.setPath("log" + String.format("%04d", i));
            em.persist(lf);
        }
    } finally {
        if (em.getTransaction().isActive()) {
            em.getTransaction().commit();
        }
        em.close();
        factory.close();
    }
}

From source file:org.apache.james.mailbox.jpa.mail.JPAModSeqProvider.java

@Override
protected long lockedNextModSeq(MailboxSession session, Mailbox mailbox) throws MailboxException {
    EntityManager manager = null;
    try {/*from  w  w  w.j  ava 2  s .  c o  m*/
        manager = factory.createEntityManager();
        manager.getTransaction().begin();
        JPAId mailboxId = (JPAId) mailbox.getMailboxId();
        JPAMailbox m = manager.find(JPAMailbox.class, mailboxId.getRawId());
        long modSeq = m.consumeModSeq();
        manager.persist(m);
        manager.getTransaction().commit();
        return modSeq;
    } catch (PersistenceException e) {
        if (manager != null && manager.getTransaction().isActive()) {
            manager.getTransaction().rollback();
        }
        throw new MailboxException("Unable to save highest mod-sequence for mailbox " + mailbox, e);
    } finally {
        if (manager != null) {
            manager.close();
        }
    }
}

From source file:org.cesecore.audit.impl.queued.entity.LogManagementData.java

public void save(final EntityManager em) {
    em.persist(this);
}

From source file:de.iai.ilcd.model.dao.AbstractDao.java

/**
 * Default persist/*  ww  w  .j  a va2 s .  c  o m*/
 * 
 * @param obj
 *            object to persist
 * @throws PersistException
 *             on errors (transaction is being rolled back)
 */
public void persist(T obj) throws PersistException {
    if (obj == null) {
        return;
    }
    EntityManager em = PersistenceUtil.getEntityManager();
    EntityTransaction t = em.getTransaction();

    try {
        t.begin();
        em.persist(obj);
        t.commit();
    } catch (Exception e) {
        t.rollback();
        throw new PersistException(e.getMessage(), e);
    }
}

From source file:com.nokia.helium.metadata.DerbyFactoryManagerCreator.java

public synchronized EntityManagerFactory create(File database) throws MetadataException {
    EntityManagerFactory factory;// w  w w  .  j a  v  a  2 s. c o  m
    String name = "metadata";
    Hashtable<String, String> persistProperties = new Hashtable<String, String>();
    persistProperties.put("javax.persistence.jdbc.driver", "org.apache.derby.jdbc.EmbeddedDriver");
    // This swallow all the output log from derby.
    System.setProperty("derby.stream.error.field",
            "com.nokia.helium.metadata.DerbyFactoryManagerCreator.DEV_NULL");
    persistProperties.put("javax.persistence.jdbc.url", "jdbc:derby:" + database.getAbsolutePath());
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT, "false");
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_REFERENCE_MODE, "WEAK");
    persistProperties.put(PersistenceUnitProperties.BATCH_WRITING, "JDBC");
    persistProperties.put("eclipselink.read-only", "true");
    persistProperties.put(PersistenceUnitProperties.LOGGING_LEVEL, "warning");
    if (database.exists()) {
        if (!checkDatabaseIntegrity(database)) {
            try {
                FileUtils.forceDelete(database);
            } catch (java.io.IOException iex) {
                throw new MetadataException("Failed deleting corrupted db: " + iex, iex);
            }
        } else {
            return Persistence.createEntityManagerFactory(name, persistProperties);
        }
    }
    persistProperties.put("javax.persistence.jdbc.url", "jdbc:derby:" + database + ";create=true");
    persistProperties.put(PersistenceUnitProperties.DDL_GENERATION, "create-tables");
    persistProperties.put(PersistenceUnitProperties.DDL_GENERATION_MODE, "database");
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_CLOSE_ON_COMMIT, "false");
    persistProperties.put(PersistenceUnitProperties.PERSISTENCE_CONTEXT_REFERENCE_MODE, "WEAK");
    persistProperties.put(PersistenceUnitProperties.BATCH_WRITING, "JDBC");
    persistProperties.put("eclipselink.read-only", "true");
    factory = Persistence.createEntityManagerFactory(name, persistProperties);
    EntityManager entityManager = factory.createEntityManager();
    // Pushing default data into the current schema
    try {
        entityManager.getTransaction().begin();
        // Version of the schema is pushed.
        entityManager.persist(new Version());
        // Default set of severity is pushed.
        for (SeverityEnum.Severity severity : SeverityEnum.Severity.values()) {
            Severity pData = new Severity();
            pData.setSeverity(severity.toString());
            entityManager.persist(pData);
        }
        entityManager.getTransaction().commit();
    } finally {
        if (entityManager.getTransaction().isActive()) {
            entityManager.getTransaction().rollback();
            entityManager.clear();
        }
        entityManager.close();
    }
    return factory;
}

From source file:de.zib.gndms.infra.model.GridEntityModelHandler.java

/**
 * Stores a new model in the persistent store
 *
 * @param emParam the EntityManager to be used or null for an EM from this handler's system
 * @param model/*  w  w w  .  j  av  a2 s  .c om*/
 */
final public @NotNull M persistModel(final EntityManager emParam, final @NotNull M model) {
    return txRun(emParam, new Function<EntityManager, M>() {
        public M apply(@com.google.common.base.Nullable @NotNull EntityManager em) {
            em.persist(model);
            return model;
        }
    });
}

From source file:br.usp.ime.lapessc.xflow2.core.VCSMiner.java

private void buildAndStoreCommit(VCSMiningProject miningProject, CommitDTO commitDTO) {

    Commit commit = new Commit();

    commit.setAuthor(getAuthor(commitDTO));
    commit.setComment(commitDTO.getComment());
    commit.setDate(commitDTO.getDate());
    commit.setRevision(commitDTO.getRevision());
    commit.setVcsMiningProject(miningProject);
    commit.setEntryFiles(getEntryFiles(commitDTO));
    commit.setEntryFolders(getEntryFolders(commitDTO));

    try {//w  w w. ja  v a 2  s .  co  m
        final EntityManager manager = DatabaseManager.getDatabaseSession();
        manager.getTransaction().begin();
        manager.persist(commit);
        manager.getTransaction().commit();
    } catch (DatabaseException e) {
        e.printStackTrace();
    }

    fixOperationType(commit);

    //Fix parent folder for folders
    for (Folder folder : commit.getEntryFolders()) {
        fixFolder(folder, commit);
    }

    //Fix parent folder for files
    setParentFolders(commit);

    setDeletedOnForFileArtifacts(commit);
    setDeletedOnForFolders(commit);

    if (miningProject.getMiningSettings().isCodeDownloadEnabled()) {
        setLocMeasures(commit);
    }

    try {
        final EntityManager manager = DatabaseManager.getDatabaseSession();
        manager.getTransaction().begin();
        manager.flush();
        manager.getTransaction().commit();
        manager.clear();
    } catch (DatabaseException e) {
        e.printStackTrace();
    }
}