Java Code Examples for javax.persistence.EntityManager#unwrap()

The following examples show how to use javax.persistence.EntityManager#unwrap() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
@Override
@Nullable
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
		throws PersistenceException, SQLException, TransactionException {

	if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
		// Pass custom isolation level on to EclipseLink's DatabaseLogin configuration
		// (since Spring 4.1.2)
		UnitOfWork uow = entityManager.unwrap(UnitOfWork.class);
		uow.getLogin().setTransactionIsolation(definition.getIsolationLevel());
	}

	entityManager.getTransaction().begin();

	if (!definition.isReadOnly() && !this.lazyDatabaseTransaction) {
		// Begin an early transaction to force EclipseLink to get a JDBC Connection
		// so that Spring can manage transactions with JDBC as well as EclipseLink.
		entityManager.unwrap(UnitOfWork.class).beginEarlyTransaction();
	}

	return null;
}
 
Example 2
Source Project: HibernateTips   File: TestStream.java    License: MIT License 6 votes vote down vote up
@Test
public void resultsAsList() {
	log.info("... resultsAsList ...");

	EntityManager em = emf.createEntityManager();
	em.getTransaction().begin();
	Session session = em.unwrap(Session.class);
	
	List<Book> books = session.createQuery("SELECT b FROM Book b", Book.class).getResultList();
	books.stream()
	    .map(b -> b.getTitle() + " was published on " + b.getPublishingDate())
	    .forEach(m -> log.info(m));
	
	em.getTransaction().commit();		
	em.close();
}
 
Example 3
private static void updateNaturalId(EntityManagerFactory emf, Map<String, Counts> counts) {
    Statistics stats = getStatistics(emf);

    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();

    final Session session = em.unwrap(Session.class);
    final NaturalIdLoadAccess<Citizen> loader = session.byNaturalId(Citizen.class);
    loader.using("ssn", "45989213T");
    Citizen citizen = loader.load();
    String expected = "Stark";
    if (!citizen.getLastname().equals(expected))
        throw new RuntimeException("Incorrect citizen: " + citizen.getLastname() + ", expected: " + expected);

    citizen.setSsn("78902007R");

    transaction.commit();
    em.close();

    assertRegionStats(counts, stats);
}
 
Example 4
private static void verifyFindCitizenByNaturalId(EntityManagerFactory emf, String ssn, String expectedLastName,
        Map<String, Counts> counts) {
    Statistics stats = getStatistics(emf);

    EntityManager em = emf.createEntityManager();
    EntityTransaction transaction = em.getTransaction();
    transaction.begin();

    final Session session = em.unwrap(Session.class);
    final NaturalIdLoadAccess<Citizen> loader = session.byNaturalId(Citizen.class);
    loader.using("ssn", ssn);
    Citizen citizen = loader.load();
    if (!citizen.getLastname().equals(expectedLastName))
        throw new RuntimeException("Incorrect citizen: " + citizen.getLastname() + ", expected: " + expectedLastName);

    transaction.commit();
    em.close();

    assertRegionStats(counts, stats);
}
 
Example 5
@Override
public SecurityIdentity authenticate(EntityManager em,
        UsernamePasswordAuthenticationRequest request) {

    Session session = em.unwrap(Session.class);
    SimpleNaturalIdLoadAccess<PlainUserEntity> naturalIdLoadAccess = session.bySimpleNaturalId(PlainUserEntity.class);
    PlainUserEntity user = naturalIdLoadAccess.load(request.getUsername());
    //        Query query = em.createQuery("FROM PlainUserEntity WHERE name = :name");
    //        query.setParameter("name", request.getUsername());
    //        PlainUserEntity user = getSingleUser(query);
    if (user == null)
        return null;

    // for MCF:
    //               Password storedPassword = getMcfPasword(user.pass);
    // for clear:
    Password storedPassword = getClearPassword(user.pass);

    QuarkusSecurityIdentity.Builder builder = checkPassword(storedPassword, request);

    addRoles(builder, user.role);
    return builder.build();
}
 
Example 6
@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
		throws PersistenceException, SQLException, TransactionException {

	if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
		// Pass custom isolation level on to EclipseLink's DatabaseLogin configuration
		// (since Spring 4.1.2)
		UnitOfWork uow = entityManager.unwrap(UnitOfWork.class);
		uow.getLogin().setTransactionIsolation(definition.getIsolationLevel());
	}

	entityManager.getTransaction().begin();

	if (!definition.isReadOnly() && !this.lazyDatabaseTransaction) {
		// Begin an early transaction to force EclipseLink to get a JDBC Connection
		// so that Spring can manage transactions with JDBC as well as EclipseLink.
		entityManager.unwrap(UnitOfWork.class).beginEarlyTransaction();
	}

	return null;
}
 
Example 7
Source Project: HibernateTips   File: TestQueryCache.java    License: MIT License 6 votes vote down vote up
@Test
public void selectAuthors() {
	log.info("... selectAuthors ...");

	EntityManager em = emf.createEntityManager();
	em.getTransaction().begin();

	Session s = em.unwrap(Session.class);
	Query<Author> q = s.createQuery("SELECT a FROM Author a WHERE id = :id", Author.class);
	q.setParameter("id", 1L);
	q.setCacheable(true);
	log.info(q.getSingleResult());
	
	log.info(q.getSingleResult());

	em.getTransaction().commit();
	em.close();
}
 
Example 8
@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
		throws PersistenceException, SQLException, TransactionException {

	if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
		// Pass custom isolation level on to EclipseLink's DatabaseLogin configuration
		// (since Spring 4.1.2)
		UnitOfWork uow = entityManager.unwrap(UnitOfWork.class);
		uow.getLogin().setTransactionIsolation(definition.getIsolationLevel());
	}

	entityManager.getTransaction().begin();

	if (!definition.isReadOnly() && !this.lazyDatabaseTransaction) {
		// Begin an early transaction to force EclipseLink to get a JDBC Connection
		// so that Spring can manage transactions with JDBC as well as EclipseLink.
		entityManager.unwrap(UnitOfWork.class).beginEarlyTransaction();
	}

	return null;
}
 
Example 9
@Override
public <S extends FailureDetail> S save(S entity) {
  EntityManager entityManager = entityManagerFactory.createEntityManager();
  Session session = entityManager.unwrap(Session.class);
  Transaction tx = session.beginTransaction();
  if (entity.getFailureCount() == 0) {
    session.save(entity);
  } else {
    session.update(entity);
  }
  tx.commit();
  return entity;
}
 
Example 10
protected void executeDML(EntityManager entityManager, String... sqls) {
    Session session = entityManager.unwrap(Session.class);
    for (String sql : sqls) {
        try {
            session.doWork(connection -> {
                executeStatement(connection, sql);
            });
        } catch (Exception e) {
            LOGGER.error(
                    String.format("Error executing statement: %s", sql), e
            );
        }
    }
}
 
Example 11
private static void verifyEntities(EntityManager entityManager, Class<?> entityClass) {
  Session session = entityManager.unwrap(Session.class);
  List<?> entityList =
      session.createQuery(
          "from " + entityClass.getSimpleName(), entityClass).list();
  assertThat(entityList).hasSize(1);
}
 
Example 12
Source Project: HibernateTips   File: TestNaturalId.java    License: MIT License 5 votes vote down vote up
@Test
public void simpleNaturalId() {
	log.info("... simpleNaturalId ...");

	EntityManager em = emf.createEntityManager();
	em.getTransaction().begin();
	Session session = em.unwrap(Session.class);

	Book b = session.bySimpleNaturalId(Book.class)
			.load("123-4567890123");
	Assert.assertEquals(new Long(1), b.getId());

	em.getTransaction().commit();
	em.close();
}
 
Example 13
private Session createEntityManagerWithStatsCleared() {
   EntityManager em = emf.createEntityManager();
   emf.unwrap(SessionFactory.class).getStatistics().clear();
   // JPA's EntityManager is not AutoCloseable,
   // but Hibernate's Session is,
   // so unwrap it to make it easier to close after use.
   return em.unwrap(Session.class);
}
 
Example 14
public DatabaseReadOnlyNetwork(EntityManager entityManager, boolean isShortTerm) {
	super(new EntityManagerImpl(entityManager.unwrap(ServerSession.class), SynchronizationType.UNSYNCHRONIZED), isShortTerm);
	ServerSession server = entityManager.unwrap(ServerSession.class);
	if (!server.getProperties().containsKey("network")) {
		server.setProperty("network", this);
	}
}
 
Example 15
/**
 * This method returns the current session for queries on the database through hibernate
 * 
 * @return Session current session object
 */
public Session getSession() {
    EntityManager currentEntityManager = MCREntityManagerProvider.getCurrentEntityManager();
    Session session = currentEntityManager.unwrap(Session.class);
    if (!session.isOpen()) {
        LOGGER.warn("Hibernate session {} is closed.", Integer.toHexString(session.hashCode()));
    }
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Returning session: {} open: {}", Integer.toHexString(session.hashCode()), session.isOpen());
    }
    return session;
}
 
Example 16
public Session getCurrentSession(EntityManager em) {
	try { 
		return em.unwrap(Session.class);
	} catch (Exception e) {
		logger.error("Error in getCurrentSession()", e);
	}
	return null;
}
 
Example 17
@Override
protected Query getEntityQuery1(EntityManager entityManager) {
    Session session = entityManager.unwrap(Session.class);
    return session.getNamedQuery(QUERY_NAME_1);
}
 
Example 18
Source Project: cuba   File: CubaEclipseLinkJpaDialect.java    License: Apache License 2.0 4 votes vote down vote up
@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 {
            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 {} sec", timeoutSec);
        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);
}
 
Example 19
protected Session getSession(EntityManager entityManager) {
	return entityManager.unwrap(Session.class);
}
 
Example 20
public static SQLQuery toSQLQuery(EntityManager em, String nativeQuery, Object beanOrMap) {
    Session session = em.unwrap(Session.class);
    SQLQuery query = session.createSQLQuery(nativeQuery);
    setParams(query, beanOrMap);
    return query;
}