Example usage for javax.persistence EntityManager unwrap

List of usage examples for javax.persistence EntityManager unwrap

Introduction

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

Prototype

public <T> T unwrap(Class<T> cls);

Source Link

Document

Return an object of the specified type to allow access to the provider-specific API.

Usage

From source file:com.chiralbehaviors.CoRE.kernel.KernelUtil.java

public static void clear(EntityManager em) throws SQLException {
    Connection connection = em.unwrap(Connection.class);
    connection.setAutoCommit(false);/* w ww .j  a v a 2  s  .c o m*/
    alterTriggers(connection, false);
    ResultSet r = connection.createStatement().executeQuery(KernelUtil.SELECT_TABLE);
    while (r.next()) {
        String table = r.getString("name");
        String query = String.format("DELETE FROM %s", table);
        connection.createStatement().execute(query);
    }
    r.close();
    alterTriggers(connection, true);
    CACHED_KERNEL.set(null);
    connection.commit();
}

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

/** Do a full export of the database in DBUnit format.
 * @param exportFilename The name of the file into which the
 *      export is to go./*w  ww . java2 s  . c  o m*/
 * @throws DatabaseUnitException If a problem with DBUnit.
 * @throws HibernateException If a problem getting the underlying
 *          JDBC connection.
 * @throws IOException If a problem writing the export.
 * @throws SQLException If DBUnit has a problem performing
 *           performing JDBC operations.
 */
public static void exportFullDBData(final String exportFilename)
        throws DatabaseUnitException, HibernateException, IOException, SQLException {
    EntityManager em = DBContext.getEntityManager();
    try (Connection conn = em.unwrap(SessionImpl.class).connection()) {
        IDatabaseConnection connection = new H2Connection(conn, null);
        IDataSet fullDataSet = connection.createDataSet();
        FlatXmlDataSet.write(fullDataSet, new FileOutputStream(exportFilename));
    }
    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.//from  w w w  . j a  v a  2 s  . c  o m
 * @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: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 .  jav a 2  s.co  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:com.chiralbehaviors.CoRE.kernel.Bootstrap.java

public Bootstrap(EntityManager em) throws SQLException {
    connection = em.unwrap(Connection.class);
    connection.setAutoCommit(false);//w  ww  .  j  av  a 2s .c  om
    this.em = em;
}

From source file:com.haulmont.cuba.core.sys.CubaEclipseLinkJpaDialect.java

@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
        throws PersistenceException, SQLException, TransactionException {
    Object result = super.beginTransaction(entityManager, definition);
    Preconditions.checkState(result == null, "Transactional data should be null for EclipseLink dialect");

    // Read default timeout every time - may be somebody wants to change it on the fly
    int defaultTimeout = 0;
    String defaultTimeoutProp = AppContext.getProperty("cuba.defaultQueryTimeoutSec");
    if (!"0".equals(defaultTimeoutProp) && !StringUtils.isBlank(defaultTimeoutProp)) {
        try {/*  w  w  w  . j a v a 2 s.c o  m*/
            defaultTimeout = Integer.parseInt(defaultTimeoutProp);
        } catch (NumberFormatException e) {
            log.error("Invalid cuba.defaultQueryTimeoutSec value", e);
        }
    }

    int timeoutSec = 0;
    if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT)
        timeoutSec = definition.getTimeout();
    else if (defaultTimeout != 0)
        timeoutSec = defaultTimeout;

    if (timeoutSec != 0) {
        log.trace("Applying query timeout " + timeoutSec + "sec");
        if (entityManager instanceof JpaEntityManager) {
            UnitOfWork unitOfWork = ((JpaEntityManager) entityManager).getUnitOfWork();
            if (unitOfWork != null) {
                //setup delay in seconds on unit of work
                unitOfWork.setQueryTimeoutDefault(timeoutSec);
            }
        }

        String s = DbmsSpecificFactory.getDbmsFeatures().getTransactionTimeoutStatement();
        if (s != null) {
            Connection connection = entityManager.unwrap(Connection.class);
            try (Statement statement = connection.createStatement()) {
                statement.execute(String.format(s, timeoutSec * 1000));
            }
        }
    }

    return new CubaEclipseLinkTransactionData(entityManager);
}

From source file:org.artificer.repository.hibernate.HibernateUtil.java

public static void evict(Class clazz, Serializable id, EntityManager entityManager) {
    entityManager.unwrap(Session.class).getSessionFactory().getCache().evictEntity(clazz, id);
}

From source file:org.broadleafcommerce.common.util.dao.DynamicDaoHelperImpl.java

@Override
public Field getIdField(Class<?> clazz, EntityManager em) {
    clazz = getNonProxyImplementationClassIfNecessary(clazz);
    ClassMetadata metadata = em.unwrap(Session.class).getSessionFactory().getClassMetadata(clazz);
    Field idField = ReflectionUtils.findField(clazz, metadata.getIdentifierPropertyName());
    idField.setAccessible(true);// www .  ja  v  a 2s  . c o  m
    return idField;
}

From source file:org.broadleafcommerce.common.util.UpdateExecutor.java

/**
 * Perform an update query using a String template and params. Note, this is only intended for special
 * usage with update queries that have an IN clause at the end. This implementation uses Hibernate Session
 * directly to avoid a problem with assigning NULL values. The query should be written in native SQL.
 * </p>/*from w w  w .jav a  2  s.  co m*/
 * An example looks like: 'UPDATE BLC_SNDBX_WRKFLW_ITEM SET SCHEDULED_DATE = ? WHERE WRKFLW_SNDBX_ITEM_ID IN (%s)'
 *
 * @param em The entity manager to use for the persistence operation
 * @param template the overall update sql template. The IN clause parameter should be written using 'IN (%s)'.
 * @param params any other params that are present in the sql template, other than the IN clause. Should be written using '?'. Should be in order. Can be null.
 * @param types the {@link org.hibernate.type.Type} instances that identify the types for the params. Should be in order and match the length of params. Can be null.
 * @param ids the ids to include in the IN clause.
 * @return the total number of records updated in the database
 */
public static int executeUpdateQuery(EntityManager em, String template, Object[] params, Type[] types,
        List<Long> ids) {
    int response = 0;
    List<Long[]> runs = buildRuns(ids);
    for (Long[] run : runs) {
        String queryString = String.format(template, buildInClauseTemplate(run.length));
        SQLQuery query = em.unwrap(Session.class).createSQLQuery(queryString);
        int counter = 0;
        if (!ArrayUtils.isEmpty(params)) {
            for (Object param : params) {
                query.setParameter(counter, param, types[counter]);
                counter++;
            }
        }
        for (Long id : run) {
            query.setLong(counter, id);
            counter++;
        }
        response += query.executeUpdate();
    }
    return response;
}

From source file:org.broadleafcommerce.openadmin.security.ClassNameRequestParamValidationServiceImpl.java

@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
    EntityManager em = factory.createEntityManager();
    if (em != null) {
        helper.initializeEntityWhiteList(em.unwrap(Session.class).getSessionFactory(), "blPU");
    } else {//from  w w  w .  ja v  a  2s .  c om
        throw new RuntimeException("Unable to initialize the entity classname whitelist");
    }
}