use of jakarta.persistence.EntityManagerFactory in project spring-framework by spring-projects.
the class OpenEntityManagerInViewFilter method doFilterInternal.
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
EntityManagerFactory emf = lookupEntityManagerFactory(request);
boolean participate = false;
WebAsyncManager asyncManager = WebAsyncUtils.getAsyncManager(request);
String key = getAlreadyFilteredAttributeName();
if (TransactionSynchronizationManager.hasResource(emf)) {
// Do not modify the EntityManager: just set the participate flag.
participate = true;
} else {
boolean isFirstRequest = !isAsyncDispatch(request);
if (isFirstRequest || !applyEntityManagerBindingInterceptor(asyncManager, key)) {
logger.debug("Opening JPA EntityManager in OpenEntityManagerInViewFilter");
try {
EntityManager em = createEntityManager(emf);
EntityManagerHolder emHolder = new EntityManagerHolder(em);
TransactionSynchronizationManager.bindResource(emf, emHolder);
AsyncRequestInterceptor interceptor = new AsyncRequestInterceptor(emf, emHolder);
asyncManager.registerCallableInterceptor(key, interceptor);
asyncManager.registerDeferredResultInterceptor(key, interceptor);
} catch (PersistenceException ex) {
throw new DataAccessResourceFailureException("Could not create JPA EntityManager", ex);
}
}
}
try {
filterChain.doFilter(request, response);
} finally {
if (!participate) {
EntityManagerHolder emHolder = (EntityManagerHolder) TransactionSynchronizationManager.unbindResource(emf);
if (!isAsyncStarted(request)) {
logger.debug("Closing JPA EntityManager in OpenEntityManagerInViewFilter");
EntityManagerFactoryUtils.closeEntityManager(emHolder.getEntityManager());
}
}
}
}
use of jakarta.persistence.EntityManagerFactory in project jOOQ by jOOQ.
the class Setup method run.
// This class sets up an EntityManager and configures the jOOQ DSLContext
// ----------------------------------------------------------------------
static void run(BiConsumer<EntityManager, DSLContext> consumer) throws Exception {
Connection connection = null;
EntityManagerFactory emf = null;
EntityManager em = null;
try {
// Bootstrapping JDBC:
Class.forName("org.h2.Driver");
connection = new LoggingConnection(DriverManager.getConnection("jdbc:h2:mem:jooq-jpa-example", "sa", ""));
final Connection c = connection;
// Creating an in-memory H2 database from our entities
MetadataSources metadata = new MetadataSources(new StandardServiceRegistryBuilder().applySetting("hibernate.dialect", "org.hibernate.dialect.H2Dialect").applySetting("javax.persistence.schema-generation-connection", connection).applySetting("javax.persistence.create-database-schemas", true).applySetting(AvailableSettings.CONNECTION_PROVIDER, new ConnectionProvider() {
@SuppressWarnings("rawtypes")
@Override
public boolean isUnwrappableAs(Class unwrapType) {
return false;
}
@Override
public <T> T unwrap(Class<T> unwrapType) {
return null;
}
@Override
public Connection getConnection() {
return c;
}
@Override
public void closeConnection(Connection conn) throws SQLException {
}
@Override
public boolean supportsAggressiveRelease() {
return true;
}
}).build());
metadata.addAnnotatedClass(Actor.class);
metadata.addAnnotatedClass(Film.class);
metadata.addAnnotatedClass(Language.class);
SchemaExport export = new SchemaExport();
export.create(EnumSet.of(TargetType.DATABASE), metadata.buildMetadata());
Map<Object, Object> props = new HashMap<>();
DataSource ds = new SingleConnectionDataSource(connection);
props.put("hibernate.connection.datasource", ds);
props.put("hibernate.archive.autodetection", "");
emf = new HibernatePersistenceProvider().createContainerEntityManagerFactory(pui(ds), props);
em = emf.createEntityManager();
final EntityManager e = em;
// Run some Hibernate / jOOQ logic inside of a transaction
em.getTransaction().begin();
data(em);
consumer.accept(em, new DefaultConfiguration().set(connection).set(onStart(ctx -> e.flush())).dsl());
em.getTransaction().commit();
} finally {
if (em != null)
em.close();
if (emf != null)
emf.close();
if (connection != null)
connection.close();
}
}
use of jakarta.persistence.EntityManagerFactory in project spring-framework by spring-projects.
the class PersistenceContextTransactionTests method setup.
@BeforeEach
public void setup() {
factory = mock(EntityManagerFactory.class);
manager = mock(EntityManager.class);
tx = mock(EntityTransaction.class);
JpaTransactionManager tm = new JpaTransactionManager(factory);
tt = new TransactionTemplate(tm);
given(factory.createEntityManager()).willReturn(manager);
given(manager.getTransaction()).willReturn(tx);
given(manager.isOpen()).willReturn(true);
bean = new EntityManagerHoldingBean();
@SuppressWarnings("serial") PersistenceAnnotationBeanPostProcessor pabpp = new PersistenceAnnotationBeanPostProcessor() {
@Override
protected EntityManagerFactory findEntityManagerFactory(@Nullable String unitName, String requestingBeanName) {
return factory;
}
};
pabpp.postProcessProperties(null, bean, "bean");
assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty()).isTrue();
assertThat(TransactionSynchronizationManager.isSynchronizationActive()).isFalse();
}
use of jakarta.persistence.EntityManagerFactory in project spring-framework by spring-projects.
the class PersistenceInjectionTests method testPrivatePersistenceContextField.
@Test
public void testPrivatePersistenceContextField() throws Exception {
mockEmf = mock(EntityManagerFactory.class, withSettings().serializable());
GenericApplicationContext gac = new GenericApplicationContext();
gac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", mockEmf);
gac.registerBeanDefinition("annotationProcessor", new RootBeanDefinition(PersistenceAnnotationBeanPostProcessor.class));
gac.registerBeanDefinition(DefaultPrivatePersistenceContextField.class.getName(), new RootBeanDefinition(DefaultPrivatePersistenceContextField.class));
gac.registerBeanDefinition(FactoryBeanWithPersistenceContextField.class.getName(), new RootBeanDefinition(FactoryBeanWithPersistenceContextField.class));
gac.refresh();
DefaultPrivatePersistenceContextField bean = (DefaultPrivatePersistenceContextField) gac.getBean(DefaultPrivatePersistenceContextField.class.getName());
FactoryBeanWithPersistenceContextField bean2 = (FactoryBeanWithPersistenceContextField) gac.getBean("&" + FactoryBeanWithPersistenceContextField.class.getName());
assertThat(bean.em).isNotNull();
assertThat(bean2.em).isNotNull();
assertThat(SerializationTestUtils.serializeAndDeserialize(bean.em)).isNotNull();
assertThat(SerializationTestUtils.serializeAndDeserialize(bean2.em)).isNotNull();
}
use of jakarta.persistence.EntityManagerFactory in project spring-framework by spring-projects.
the class OpenEntityManagerInViewTests method testOpenEntityManagerInViewFilter.
@Test
public void testOpenEntityManagerInViewFilter() throws Exception {
given(manager.isOpen()).willReturn(true);
final EntityManagerFactory factory2 = mock(EntityManagerFactory.class);
final EntityManager manager2 = mock(EntityManager.class);
given(factory2.createEntityManager()).willReturn(manager2);
given(manager2.isOpen()).willReturn(true);
MockServletContext sc = new MockServletContext();
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
wac.getDefaultListableBeanFactory().registerSingleton("entityManagerFactory", factory);
wac.getDefaultListableBeanFactory().registerSingleton("myEntityManagerFactory", factory2);
wac.refresh();
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
MockHttpServletRequest request = new MockHttpServletRequest(sc);
MockHttpServletResponse response = new MockHttpServletResponse();
MockFilterConfig filterConfig = new MockFilterConfig(wac.getServletContext(), "filter");
MockFilterConfig filterConfig2 = new MockFilterConfig(wac.getServletContext(), "filter2");
filterConfig2.addInitParameter("entityManagerFactoryBeanName", "myEntityManagerFactory");
final OpenEntityManagerInViewFilter filter = new OpenEntityManagerInViewFilter();
filter.init(filterConfig);
final OpenEntityManagerInViewFilter filter2 = new OpenEntityManagerInViewFilter();
filter2.init(filterConfig2);
final FilterChain filterChain = (servletRequest, servletResponse) -> {
assertThat(TransactionSynchronizationManager.hasResource(factory)).isTrue();
servletRequest.setAttribute("invoked", Boolean.TRUE);
};
final FilterChain filterChain2 = (servletRequest, servletResponse) -> {
assertThat(TransactionSynchronizationManager.hasResource(factory2)).isTrue();
filter.doFilter(servletRequest, servletResponse, filterChain);
};
FilterChain filterChain3 = new PassThroughFilterChain(filter2, filterChain2);
assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse();
filter2.doFilter(request, response, filterChain3);
assertThat(TransactionSynchronizationManager.hasResource(factory)).isFalse();
assertThat(TransactionSynchronizationManager.hasResource(factory2)).isFalse();
assertThat(request.getAttribute("invoked")).isNotNull();
verify(manager).close();
verify(manager2).close();
wac.close();
}
Aggregations