Example usage for javax.persistence EntityManager close

List of usage examples for javax.persistence EntityManager close

Introduction

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

Prototype

public void close();

Source Link

Document

Close an application-managed entity manager.

Usage

From source file:au.org.ands.vocabs.toolkit.db.AccessPointUtils.java

/** Get all access points of a certain type for a version.
 * @param version The version./*from   w w w .ja v a2  s  .  co m*/
 * @param type The type of access point to look for.
 * @return The list of access points for this version.
 */
public static List<AccessPoint> getAccessPointsForVersionAndType(final Version version, final String type) {
    EntityManager em = DBContext.getEntityManager();
    TypedQuery<AccessPoint> q = em
            .createNamedQuery(AccessPoint.GET_ACCESSPOINTS_FOR_VERSION_AND_TYPE, AccessPoint.class)
            .setParameter(AccessPoint.GET_ACCESSPOINTS_FOR_VERSION_AND_TYPE_VERSIONID, version.getId())
            .setParameter(AccessPoint.GET_ACCESSPOINTS_FOR_VERSION_AND_TYPE_TYPE, type);
    List<AccessPoint> aps = q.getResultList();
    em.close();
    return aps;
}

From source file:au.org.ands.vocabs.toolkit.db.AccessPointUtils.java

/** Delete all access points of a certain type for a version.
 * @param version The version./*w  ww .  j av a2  s  .c  o m*/
 * @param type The type of access point to look for.
 */
public static void deleteAccessPointsForVersionAndType(final Version version, final String type) {
    EntityManager em = DBContext.getEntityManager();
    em.getTransaction().begin();
    Query q = em.createNamedQuery(AccessPoint.DELETE_ACCESSPOINTS_FOR_VERSION_AND_TYPE)
            .setParameter(AccessPoint.DELETE_ACCESSPOINTS_FOR_VERSION_AND_TYPE_VERSIONID, version.getId())
            .setParameter(AccessPoint.DELETE_ACCESSPOINTS_FOR_VERSION_AND_TYPE_TYPE, type);
    q.executeUpdate();
    em.getTransaction().commit();
    em.close();
}

From source file:au.org.ands.vocabs.toolkit.test.arquillian.ArquillianTestUtils.java

/** Clear the database.
 * @throws DatabaseUnitException If a problem with DBUnit.
 * @throws HibernateException If a problem getting the underlying
 *          JDBC connection./*  w ww . ja v a 2s.  c  om*/
 * @throws IOException If a problem getting test data for DBUnit.
 * @throws SQLException If DBUnit has a problem performing
 *           performing JDBC operations.
 */
public static void clearDatabase() throws DatabaseUnitException, HibernateException, IOException, SQLException {
    EntityManager em = DBContext.getEntityManager();
    try (Connection conn = em.unwrap(SessionImpl.class).connection()) {

        IDatabaseConnection connection = new H2Connection(conn, null);

        logger.info("doing clean_insert");
        FlatXmlDataSet dataset = new FlatXmlDataSetBuilder()
                .setMetaDataSetFromDtd(getResourceAsInputStream("test/dbunit-toolkit-export-choice.dtd"))
                .build(getResourceAsInputStream("test/blank-dbunit.xml"));

        DatabaseOperation.DELETE_ALL.execute(connection, dataset);
        // Force commit at the JDBC level, as closing the EntityManager
        // does a rollback!
        conn.commit();
    }
    em.close();
}

From source file:fredboat.db.entity.SearchResult.java

/**
 * @param playerManager the PlayerManager to perform encoding and decoding with
 * @param provider      the search provider that shall be used for this search
 * @param searchTerm    the query to search for
 * @param maxAgeMillis  the maximum age of the cached search result; provide a negative value for eternal cache
 * @return the cached search result; may return null for a non-existing or outdated search
 */// w  w  w.j a v a  2s  . com
public static AudioPlaylist load(AudioPlayerManager playerManager, SearchUtil.SearchProvider provider,
        String searchTerm, long maxAgeMillis) throws DatabaseNotReadyException {
    DatabaseManager dbManager = FredBoat.getDbManager();
    if (dbManager == null || !dbManager.isAvailable()) {
        throw new DatabaseNotReadyException();
    }

    EntityManager em = dbManager.getEntityManager();
    SearchResult sr;
    SearchResultId sId = new SearchResultId(provider, searchTerm);
    try {
        em.getTransaction().begin();
        sr = em.find(SearchResult.class, sId);
        em.getTransaction().commit();
    } catch (PersistenceException e) {
        log.error("Unexpected error while trying to look up a search result for provider {} and search term {}",
                provider.name(), searchTerm, e);
        throw new DatabaseNotReadyException(e);
    } finally {
        em.close();
    }

    if (sr != null && (maxAgeMillis < 0 || System.currentTimeMillis() < sr.timestamp + maxAgeMillis)) {
        return sr.getSearchResult(playerManager);
    } else {
        return null;
    }
}

From source file:com.enioka.jqm.tools.Helpers.java

static void closeQuietly(EntityManager em) {
    try {//from   w  w  w . j a  v a2  s .co m
        if (em != null) {
            if (em.getTransaction().isActive()) {
                em.getTransaction().rollback();
            }
            em.close();
        }
    } catch (Exception e) {
        // fail silently
    }
}

From source file:com.fpuna.preproceso.PreprocesoTS.java

/**
 *
 * @param trainingSetFeatureList/*from ww  w.j  a  va 2s .  c o  m*/
 */
public static void GuardarFeature(List<TrainingSetFeature> trainingSetFeatureList) {
    EntityManager entityManager = Persistence.createEntityManagerFactory("PreprocesoTSPU")
            .createEntityManager();

    entityManager.getTransaction().begin();

    Iterator<TrainingSetFeature> Iterator = trainingSetFeatureList.iterator();
    while (Iterator.hasNext()) {
        entityManager.persist(Iterator.next());
    }

    entityManager.getTransaction().commit();
    entityManager.close();
}

From source file:io.symcpe.hendrix.api.dao.TestRulesManager.java

@BeforeClass
public static void beforeClass() throws Exception {
    java.util.logging.Logger.getLogger("org.hibernate").setLevel(Level.OFF);
    Properties config = new Properties(System.getProperties());
    File db = new File(TARGET_RULES_DB);
    if (db.exists()) {
        FileUtils.deleteDirectory(db);//from   www .  java 2 s.com
    }
    config.setProperty("javax.persistence.jdbc.url", CONNECTION_STRING);
    try {
        emf = Persistence.createEntityManagerFactory("hendrix", config);
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }

    EntityManager em = emf.createEntityManager();

    Tenant tenant = new Tenant();
    tenant.setTenant_id(TENANT_ID_1);
    tenant.setTenant_name(TEST_TENANT);
    TenantManager.getInstance().createTenant(em, tenant);

    tenant = new Tenant();
    tenant.setTenant_id(TENANT_ID_2);
    tenant.setTenant_name(TEST_TENANT);
    TenantManager.getInstance().createTenant(em, tenant);

    tenant = new Tenant();
    tenant.setTenant_id(TENANT_ID_3);
    tenant.setTenant_name(TEST_TENANT);
    TenantManager.getInstance().createTenant(em, tenant);

    tenant = new Tenant();
    tenant.setTenant_id(TENANT_ID_5);
    tenant.setTenant_name(TEST_TENANT);
    TenantManager.getInstance().createTenant(em, tenant);

    em.close();
}

From source file:au.org.ands.vocabs.toolkit.test.arquillian.ArquillianTestUtils.java

/** Load a DbUnit test file into the database.
 * The file is loaded as a {@code FlatXmlDataSet}.
 * To make it more convenient to enter JSON data, the dataset is
 * wrapped as a {@code ReplacementDataSet}, and all instances
 * of '' (two contiguous apostrophes) are replaced with "
 * (one double quote)./*from   ww w  . j av a  2s . c o  m*/
 * @param testName The name of the test method. Used to generate
 *      the filename of the file to load.
 * @throws DatabaseUnitException If a problem with DBUnit.
 * @throws HibernateException If a problem getting the underlying
 *          JDBC connection.
 * @throws IOException If a problem getting test data for DBUnit.
 * @throws SQLException If DBUnit has a problem performing
 *           performing JDBC operations.
 */
public static void loadDbUnitTestFile(final String testName)
        throws DatabaseUnitException, HibernateException, IOException, SQLException {
    EntityManager em = DBContext.getEntityManager();
    try (Connection conn = em.unwrap(SessionImpl.class).connection()) {

        IDatabaseConnection connection = new H2Connection(conn, null);

        FlatXmlDataSet xmlDataset = new FlatXmlDataSetBuilder()
                .setMetaDataSetFromDtd(getResourceAsInputStream("test/dbunit-toolkit-export-choice.dtd"))
                .build(getResourceAsInputStream("test/tests/au.org.ands.vocabs.toolkit."
                        + "test.arquillian.AllArquillianTests." + testName + "/input-dbunit.xml"));
        ReplacementDataSet dataset = new ReplacementDataSet(xmlDataset);
        dataset.addReplacementSubstring("''", "\"");
        logger.info("doing clean_insert");
        DatabaseOperation.CLEAN_INSERT.execute(connection, dataset);
        // Force commit at the JDBC level, as closing the EntityManager
        // does a rollback!
        conn.commit();
    }
    em.close();
}

From source file:dao.UsuarioDao.java

public void cadastrarPessoa(Usuario usuario) {
    EntityManagerFactory factory = Persistence.createEntityManagerFactory("LoginUsersPU");
    EntityManager em = factory.createEntityManager();

    em.getTransaction().begin();// ww  w  .  ja v  a2 s  . c  o m
    em.persist(usuario);
    em.getTransaction().commit();
    em.close();
}

From source file:com.sixsq.slipstream.persistence.Run.java

public static Run load(String resourceUri) {
    EntityManager em = PersistenceUtil.createEntityManager();
    Run run = em.find(Run.class, resourceUri);
    em.close();
    return run;/*from w ww  .j a va 2s .  c o  m*/
}