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.unitils.orm.jpa.util.provider.hibernate.HibernateJpaProviderSupport.java

/**
 * Checks if the mapping of the JPA entities with the database is still correct.
 *///from  w w  w.ja va  2  s  .  c o  m
public void assertMappingWithDatabaseConsistent(EntityManager entityManager, Object configurationObject) {
    Configuration configuration = (Configuration) configurationObject;
    Dialect databaseDialect = getHibernateDatabaseDialect(configuration);

    HibernateAssert.assertMappingWithDatabaseConsistent(configuration, (Session) entityManager.getDelegate(),
            databaseDialect);
}

From source file:com.easyjf.core.dao.impl.GenericDAOImpl.java

public void flush() {
    this.getJpaTemplate().execute(new JpaCallback() {
        public Object doInJpa(EntityManager em) throws PersistenceException {
            Session session = (Session) em.getDelegate();
            session.flush();//from w ww.  ja  va2 s  .com
            return null;
        }
    });
}

From source file:fr.xebia.demo.wicket.blog.service.GenericService.java

@SuppressWarnings("unchecked")
public List<T> list() throws ServiceException {
    try {/*from  ww w  .  ja  va2 s  .co m*/
        EntityManager entityManager = currentEntityManager();

        Criteria criteria = ((Session) entityManager.getDelegate()).createCriteria(getObjectClass());
        criteria.setMaxResults(getMaxResults());
        return criteria.setCacheable(true).list();
    } catch (PersistenceException e) {
        logger.error(e.getCause(), e);
        throw new ServiceException("Can't get object list from database", e);
    } finally {
        closeEntityManager();
    }
}

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

@Test
@PerfTest(invocations = 10)/*from  w  w  w  .  j  ava  2  s  . co  m*/
public void testCRUDWithBatch() {
    Map<String, String> batchProperty = new HashMap<String, String>(1);
    batchProperty.put(PersistenceProperties.KUNDERA_BATCH_SIZE, "5");
    EntityManagerFactory emf = Persistence.createEntityManagerFactory(_PU, batchProperty);
    EntityManager em = emf.createEntityManager();
    Map<String, Client> clients = (Map<String, Client>) em.getDelegate();
    CouchDBClient client = (CouchDBClient) clients.get(_PU);
    Assert.assertEquals(5, ((Batcher) client).getBatchSize());

    final String originalName = "vivek";

    for (int i = 0; i < 9; i++) {
        PersonCouchDB object = new PersonCouchDB();
        object.setAge(32);
        object.setPersonId(ROW_KEY + i);
        object.setPersonName(originalName);
        em.persist(object);

        if (i >= 5) {
            PersonCouchDB result = (PersonCouchDB) client.find(PersonCouchDB.class, ROW_KEY + i);
            Assert.assertNull(result);
        } else if (i > 0 && i % 4 == 0) {
            PersonCouchDB result = (PersonCouchDB) client.find(PersonCouchDB.class, ROW_KEY + i);
            Assert.assertNotNull(result);
            Assert.assertEquals(result.getPersonId(), object.getPersonId());
            Assert.assertEquals(result.getAge(), object.getAge());
            Assert.assertEquals(result.getPersonName(), object.getPersonName());
        }
    }
    em.flush();
    em.clear();
    em.close();
    em = null;
}

From source file:org.hibernate.search.demo.SearchDemo.java

private void purge() {
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();/*from  ww  w . j av  a 2s.  com*/
    FullTextSession ftSession = org.hibernate.search.Search.createFullTextSession((Session) em.getDelegate());
    ftSession.purgeAll(Product.class);
    em.getTransaction().commit();
    em.close();
}

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

@Test
public void testPersistJoinTableData() throws ClientProtocolException, URISyntaxException, IOException {
    final String schemaName = "couchdatabase";
    final String tableName = "couchjointable";
    final String joinColumn = "joinColumnName";
    final String inverseJoinColumn = "inverseJoinColumnName";

    CouchDBTestUtils.createViews(new String[] { joinColumn, inverseJoinColumn }, tableName, httpHost,
            schemaName, httpClient);//from  w w w  . jav a2 s . c om
    JoinTableData joinTableData = new JoinTableData(OPERATION.INSERT, schemaName, tableName, joinColumn,
            inverseJoinColumn, null);

    String joinKey = "4";

    Integer inverseJoinKey1 = new Integer(10);
    // inverseJoinKey2 was Double earlier, changed to Integer
    //CouchDB has an issue with handling fixed precision numbers
    //So the test case was failing
    Integer inverseJoinKey2 = new Integer(12);
    Set inverseJoinKeys = new HashSet();
    inverseJoinKeys.add(inverseJoinKey1);
    inverseJoinKeys.add(inverseJoinKey2);

    joinTableData.addJoinTableRecord(joinKey, inverseJoinKeys);

    EntityManager em = emf.createEntityManager();
    Map<String, Client> clients = (Map<String, Client>) em.getDelegate();
    CouchDBClient client = (CouchDBClient) clients.get(_PU);
    client.persistJoinTable(joinTableData);

    List<String> columns = client.getColumnsById(schemaName, tableName, joinColumn, inverseJoinColumn, joinKey,
            String.class);

    Assert.assertNotNull(columns);
    Assert.assertEquals(true, !columns.isEmpty());
    Assert.assertEquals(2, columns.size());
    Assert.assertEquals(true, columns.contains(inverseJoinKey1.toString()));
    Assert.assertEquals(true, columns.contains(inverseJoinKey2.toString()));

    client.deleteByColumn(schemaName, tableName, inverseJoinColumn, inverseJoinKey1);
    client.deleteByColumn(schemaName, tableName, inverseJoinColumn, inverseJoinKey2);

    columns = client.getColumnsById(schemaName, tableName, joinColumn, inverseJoinColumn, joinKey,
            String.class);

    Assert.assertTrue(columns.isEmpty());
}

From source file:org.hibernate.search.demo.SearchDemo.java

private void index() {
    EntityManager em = emf.createEntityManager();
    em.getTransaction().begin();//w w  w  . j a v  a2s.c  o  m
    FullTextSession ftSession = org.hibernate.search.Search.createFullTextSession((Session) em.getDelegate());
    List results = ftSession.createCriteria(Product.class).list();
    for (Object obj : results) {
        ftSession.index(obj);
    }
    em.getTransaction().commit();
    em.close();

}

From source file:com.webbfontaine.valuewebb.timer.RatesUpdater.java

@Asynchronous
@Transactional//from  w  w w .  j a v  a 2  s .  c  o  m
public QuartzTriggerHandle scheduleTask(@Expiration Date when, @IntervalCron String interval) {

    HashMap<String, BigDecimal> ratesFromBank = ratesFromBank();
    if (ratesFromBank.isEmpty()) {
        LOGGER.error("No rates passed to update, check web site and source code!");
        return null;
    }

    EntityManager entityManager = Utils.getEntityManager();

    List<Rate> existingRates = entityManager.createQuery("from Rate r where r.eov is null").getResultList();

    Transaction tx = ((org.jboss.seam.persistence.HibernateSessionProxy) entityManager.getDelegate())
            .getTransaction();

    try {

        tx.begin();

        for (Rate existingRecord : existingRates) {

            BigDecimal latestRateForCurrency = ratesFromBank.get(existingRecord.getCod());

            if (latestRateForCurrency == null) {
                LOGGER.warn("Currency code '{0}' exists but absent in updates", existingRecord.getCod());
                continue;
            }

            if (existingRecord.getExch().doubleValue() != latestRateForCurrency.doubleValue()) { //i get double value because bigdecimal can return 0.2240 which is not equal to 0.224 when comparing BD values
                /* close existing rate and open new one from today */
                Date tomorrowDate = Utils.getTomorrowDate();
                existingRecord.setEov(tomorrowDate); // since scheduler works at 21:00
                Rate newRecord = new Rate(null, existingRecord.getCod(), 1, latestRateForCurrency, tomorrowDate,
                        null);
                entityManager.persist(existingRecord);
                entityManager.persist(newRecord);
                LOGGER.info("Updated Exchange rate for {0}, old: {1}, new: {2}", newRecord.getCod(),
                        existingRecord.unitRate(), newRecord.unitRate());
            }
        }

        entityManager.flush();
        tx.commit();

    } catch (Exception e) {
        LOGGER.error("Exception on updating rates", e);
        if (tx != null) {
            tx.rollback();
        }
    }

    return null;
}

From source file:it.attocchi.jpa2.JpaController.java

public <T extends Serializable> List<T> findByExample(Class<T> clazz, T anExample) throws Exception {
    List<T> res = new ArrayList<T>();

    testClazz(clazz);//from   w  ww  .ja  va 2  s .c  o m

    EntityManager em = getEntityManager();
    Session session = null;

    try {
        session = (Session) em.getDelegate();
        res = session.createCriteria(clazz).add(Example.create(anExample).excludeZeroes().enableLike()).list();
    } catch (Exception e) {
        throw e;
    } finally {
        // Close the database connection:
        if (!globalTransactionOpen) {
            // if (em.getTransaction().isActive())
            // em.getTransaction().rollback();
            closeEm(); // em.close();
        }
    }

    return res;
}

From source file:it.webappcommon.lib.jpa.ControllerStandard.java

public <T extends Serializable> List<T> findByExample(Class<T> clazz, T anExample) throws Exception {
    List<T> res = new ArrayList<T>();

    EntityManager em = getEntityManagerFactory().createEntityManager();
    Session session = null;/*w w  w  .j a v a 2 s.co  m*/
    Criteria cri = null;

    try {

        session = (Session) em.getDelegate();

        res = session.createCriteria(clazz).add(Example.create(anExample).excludeZeroes().enableLike()).list();

        // res = em.createQuery("SELECT e FROM " + clazz.getCanonicalName()
        // + " e", clazz).getResultList();

    } catch (Exception e) {
        throw e;
    } finally {
        // Close the database connection:
        if (em.getTransaction().isActive())
            em.getTransaction().rollback();
        em.close();
    }

    return res;
}