Example usage for javax.persistence EntityManager getDelegate

List of usage examples for javax.persistence EntityManager getDelegate

Introduction

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

Prototype

public Object getDelegate();

Source Link

Document

Return the underlying provider object for the EntityManager, if available.

Usage

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

private static void initDDL(EntityManager entityManager, Map<String, Object> properties) throws Exception {
    // If the DDL is not already installed in the DB, automatically do it on first use.
    SessionImplementor session = (SessionImplementor) entityManager.getDelegate();
    Connection connection = session.connection();

    if (!hasTables(connection)) {
        // our tables don't exist -- create them
        String dialect = (String) properties.get("hibernate.dialect");
        if (dialect != null) {
            String ddlFile;//from  w ww  .  ja v a 2  s.co  m
            if (dialect.contains("PostgreSQL")) {
                ddlFile = "postgres9.sql";
            } else if (dialect.contains("MySQL")) {
                ddlFile = "mysql5.sql";
            } else if (dialect.contains("Oracle")) {
                ddlFile = "oracle10.sql";
            } else if (dialect.contains("SQLServer")) {
                ddlFile = "mssql2012.sql";
            } else if (dialect.contains("DB2")) {
                ddlFile = "db2.sql";
            } else {
                ddlFile = "h2.sql";
            }

            Statement statement = null;
            try {
                URL url = HibernateUtil.class.getClassLoader().getResource("ddl/" + ddlFile);
                String ddl = IOUtils.toString(url);

                statement = connection.createStatement();
                statement.executeUpdate(ddl);
            } finally {
                if (statement != null) {
                    statement.close();
                }
                // do *not* close the connection -- it will still be used by this instance of the EntityManager
            }
        }
    }
}

From source file:org.compass.gps.device.jpa.extractor.NativeJpaHelper.java

public static EntityManager extractNativeJpa(EntityManager em) {
    if (extractors.length == 0) {
        return em;
    }/*from  w w w  .ja  v a 2  s. com*/
    EntityManager nativeEm = em;
    do {
        while (true) {
            // even though getDelegate should return the actual underlying implementation (Hibernate Session for example)
            // some app servers that wrap the EM, actually return the wrapped EM, and not the wrapped EM # getDelegate()
            Object delegate = nativeEm.getDelegate();
            if (delegate == nativeEm) {
                break;
            }
            if (delegate instanceof EntityManager) {
                nativeEm = (EntityManager) delegate;
            } else {
                break;
            }
        }
        em = nativeEm;
        for (NativeJpaExtractor extractor : extractors) {
            nativeEm = extractor.extractNative(nativeEm);
        }
    } while (nativeEm != em);

    return nativeEm;
}

From source file:org.rhq.core.domain.server.PersistenceUtility.java

public static Session getHibernateSession(EntityManager entityManager) {
    Session session;/*w  w  w  . j  a  va  2s .c o  m*/
    if (entityManager.getDelegate() instanceof EntityManagerImpl) {
        EntityManagerImpl entityManagerImpl = (EntityManagerImpl) entityManager.getDelegate();
        session = entityManagerImpl.getSession();
    } else {
        session = (Session) entityManager.getDelegate();
    }

    return session;
}

From source file:com.webbfontaine.valuewebb.action.rimm.CacheCleaner.java

public Object clean() {

    if (StringUtils.trimToNull(entityClass) != null) {

        EntityManager entityManager = Utils.getEntityManager();
        SessionFactory sf = ((Session) entityManager.getDelegate()).getSessionFactory();
        EntityPersister classMetadata = (EntityPersister) sf.getClassMetadata(entityClass);
        if (classMetadata != null && classMetadata.hasCache()) {
            LOGGER.info("Evicting cache for {0}", entityClass);
            sf.evictEntity(entityClass);
            sf.evictQueries();/*from  w w w  .j a  va 2  s . com*/
            InfoHandling.getInstance().setInfoList("Cache evicted");
        } else {
            ErrorHandling.addFacesMessageError(null, "Entity is not cached");
        }
    }
    return "";
}

From source file:org.isatools.isatab.ISATABUnloader.java

public void unload() {
    List<Study> studies = new LinkedList<Study>();

    EntityManager emgr = daoFactory.getEntityManager();
    Session session = (Session) emgr.getDelegate();
    EntityTransaction ts = emgr.getTransaction();

    if (studyAcc != null) {
        StudyDAO dao = daoFactory.getStudyDAO();
        Study study = dao.getByAcc(studyAcc);
        if (study == null) {
            log.warn("Study with accession '" + studyAcc + "' not found, no undeletion performed.");
            return;
        }/* www  . ja va  2s . c om*/
        studies.add(study);

        unloadMgr = new UnloadManager(daoFactory, study.getSubmissionTs());
        StudyUnloader unloader = (StudyUnloader) unloadMgr.getUnloader(Study.class);
        unloader.queueByAcc(studyAcc);
    } else {
        studies.addAll(daoFactory.getStudyDAO().getBySubmissionTs(unloadMgr.getSubmissionTs()));
        unloadMgr.queueAll(studies);
    }

    try {
        if (!ts.isActive()) {
            ts.begin();
        }
        unloadMgr.delete();
        ts.commit();
    } catch (HibernateException e) {
        if (ts.isActive()) {
            ts.rollback();
        }
        throw new TabInternalErrorException("Error while performing the unloading:" + e.getMessage());
    } finally {
        session.flush();
    }

    DataFilesDispatcher fileDispatcher = new DataFilesDispatcher(daoFactory.getEntityManager());
    fileDispatcher.undispatch(studies);
}

From source file:nl.b3p.datastorelinker.gui.stripes.ConvertLargeObjectsAction.java

public void convertLOBS() throws SQLException, NoSuchFieldException, IllegalArgumentException,
        IllegalAccessException, IOException {

    statusArray.put("Opening connection..");
    EntityManager em = JpaUtilServlet.getThreadEntityManager();
    Session session = (Session) em.getDelegate();
    Connection conn = session.connection();
    conn.setAutoCommit(false);/*from w  w w. j  a va  2  s .co  m*/
    DatabaseMetaData metadata = conn.getMetaData();
    statusArray.put("Digging deep to retrieve implementation");

    Field f = metadata.getClass().getDeclaredField("inner");

    f.setAccessible(true);
    Object pgconnMetadata = f.get(metadata);
    statusArray.put("Retrieving postgres connection..");
    org.postgresql.PGConnection connection = (org.postgresql.PGConnection) ((org.postgresql.jdbc4.Jdbc4DatabaseMetaData) pgconnMetadata)
            .getConnection();
    statusArray.put("Connection established");
    lom = connection.getLargeObjectAPI();
    statusArray.put("Create LargeObjectManager");
    em.getTransaction().begin();
    statusArray.put("Begin converting LOBs");
    processProcesses(em);
    processProcessesStatusses(em);

    statusArray.put("Converting finished");
    em.getTransaction().commit();
    statusArray.put("Changes saved");
}

From source file:pl.com.bottega.testutils.HibernateExtendedJpaDialect.java

/**
 * This method is overridden to set custom isolation levels on the connection
 * @param entityManager/*www.j av  a 2s  . c  om*/
 * @param definition
 * @return
 * @throws PersistenceException
 * @throws SQLException
 * @throws TransactionException
 */
@Override
public Object beginTransaction(final EntityManager entityManager, final TransactionDefinition definition)
        throws PersistenceException, SQLException, TransactionException {
    Session session = (Session) entityManager.getDelegate();
    if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
        getSession(entityManager).getTransaction().setTimeout(definition.getTimeout());
    }

    entityManager.getTransaction().begin();
    logger.debug("Transaction started");

    session.doWork(new Work() {

        public void execute(Connection connection) throws SQLException {
            logger.debug("The connection instance is {}", connection);
            logger.debug(
                    "The isolation level of the connection is {} and the isolation level set on the transaction is {}",
                    connection.getTransactionIsolation(), definition.getIsolationLevel());
            DataSourceUtils.prepareConnectionForTransaction(connection, definition);
        }
    });

    return prepareTransaction(entityManager, definition.isReadOnly(), definition.getName());
}

From source file:org.spring.data.gemfire.app.dao.vendor.SQLFireJpaUserDao.java

@Override
protected EntityManager prepare(final EntityManager entityManager) {
    Assert.notNull(entityManager, "The JPA EntityManager must not be null!");
    Assert.state(entityManager.isOpen(), "The EntityManager is closed!");

    if (entityManager.getDelegate() instanceof Session) {
        Session session = (Session) entityManager.getDelegate();

        if (session instanceof SessionImpl) {
            try {
                ((SessionImpl) session).connection()
                        .setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
                //((SessionImpl) session).connection().setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
                //((SessionImpl) session).connection().setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
                //((SessionImpl) session).connection().setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
                //((SessionImpl) session).connection().setTransactionIsolation(Connection.TRANSACTION_NONE);
            } catch (SQLException e) {
                //System.err.printf("Failed to set the JDBC Connection Transaction Isolation Level to (READ_COMMITTED)!%n%1$s%n", e);
                throw new PersistenceException(
                        "Failed to set the JDBC Connection Transaction Isolation-level to (READ_COMMITTED)!",
                        e);/*w w w.  jav a2  s. co m*/
            }
        }
    }

    return entityManager;
}

From source file:org.giwi.finistjug.camel.demo.processor.ListOfSessionsProcessor.java

@SuppressWarnings("unchecked")
@Override//www  . jav  a 2s. c om
public void process(final Exchange exchange) throws Exception {
    final List<JUGSession> listOfSessions = new ArrayList<JUGSession>();
    exchange.getIn().setBody(null);

    // Rcupration de l'entityManager
    final EntityManager em = EntityManagerUtil.getEntityManager();
    final ExpressionBuilder builder = new ExpressionBuilder();
    final ReadAllQuery databaseQuery = new ReadAllQuery(Jugpresentation.class, builder);
    final Query query = ((JpaEntityManager) em.getDelegate()).createQuery(databaseQuery);
    // excution de la requte
    try {
        final List<Jugpresentation> jugPres = query.getResultList();
        final DozerBeanMapper mapper = exchange.getContext().getRegistry().lookup("mapper",
                DozerBeanMapper.class);
        for (final Jugpresentation jugP : jugPres) {
            em.refresh(jugP);
            // mapping Dozer
            listOfSessions.add(mapper.map(jugP, JUGSession.class));
        }
    } catch (final NoResultException e) {
        // pas de rsultat trouv, c'est pas bien grave
        if (LOG.isInfoEnabled()) {
            LOG.info(e);
        }
    }
    final ListeDesSessionsResponse resp = new ListeDesSessionsResponse();
    resp.setListeDesSessions(listOfSessions);
    exchange.getIn().setBody(resp);
}

From source file:com.impetus.client.couchdb.crud.CouchDBClientTest.java

@Test
@PerfTest(invocations = 10)/*w w  w  .j  a v  a2  s . co  m*/
public void testCRUD() {
    logger.info("On testInsert");
    EntityManager em = emf.createEntityManager();
    Map<String, Client> clients = (Map<String, Client>) em.getDelegate();
    CouchDBClient client = (CouchDBClient) clients.get(_PU);
    onInsert(client);
    onUpdate(client);
    onDelete(client);
    em.close();
}