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

The following examples show how to use javax.persistence.EntityManager#unwrap() . 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 check out the related API usage on the sidebar.
Example 1
Source File: EclipseLinkJpaDialect.java    From spring-analysis-note with MIT License 9 votes vote down vote up
@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 File: InfinispanCacheJPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
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 3
Source File: EclipseLinkJpaDialect.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 4
Source File: TestQueryCache.java    From HibernateTips with 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 5
Source File: EclipseLinkJpaDialect.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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 6
Source File: UserEntityIdentityProvider.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@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 7
Source File: InfinispanCacheJPAFunctionalityTestEndpoint.java    From quarkus with Apache License 2.0 6 votes vote down vote up
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 8
Source File: TestStream.java    From HibernateTips with 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 9
Source File: InfinispanHibernateCacheSpringLocal.java    From infinispan-simple-tutorials with Apache License 2.0 5 votes vote down vote up
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 10
Source File: TestNaturalId.java    From HibernateTips with 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 11
Source File: DatabaseReadOnlyNetwork.java    From BotLibre with Eclipse Public License 1.0 5 votes vote down vote up
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 12
Source File: InterleavedTest.java    From google-cloud-spanner-hibernate with GNU Lesser General Public License v2.1 5 votes vote down vote up
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 13
Source File: AbstractTest.java    From high-performance-java-persistence with Apache License 2.0 5 votes vote down vote up
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 14
Source File: MCRHIBConnection.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 15
Source File: CommonOperations.java    From AIDR with GNU Affero General Public License v3.0 5 votes vote down vote up
public Session getCurrentSession(EntityManager em) {
	try { 
		return em.unwrap(Session.class);
	} catch (Exception e) {
		logger.error("Error in getCurrentSession()", e);
	}
	return null;
}
 
Example 16
Source File: FailureDetailRepositoryImpl.java    From rqueue with Apache License 2.0 5 votes vote down vote up
@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 17
Source File: HibernateJpaDialect.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
protected Session getSession(EntityManager entityManager) {
	return entityManager.unwrap(Session.class);
}
 
Example 18
Source File: QueryBuilder.java    From spring-data-jpa-extra with Apache License 2.0 4 votes vote down vote up
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;
}
 
Example 19
Source File: CubaEclipseLinkJpaDialect.java    From cuba with 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 20
Source File: NamedQueryPerformanceTest.java    From high-performance-java-persistence with Apache License 2.0 4 votes vote down vote up
@Override
protected Query getEntityQuery1(EntityManager entityManager) {
    Session session = entityManager.unwrap(Session.class);
    return session.getNamedQuery(QUERY_NAME_1);
}