#spring #hibernate #spring-data-jpa #spring-data
#spring #спящий режим #spring-data-jpa #spring-данные
Вопрос:
В настоящее время наша команда разрабатывает приложение, которое использует 3 разных источника данных. Пока все хорошо,
1-й — диспетчер транзакций является основным (компонент с именем TransactionManager)
2-й — находится над источником routingDataSource (предоставленным spring) с менеджером транзакций с именем disntinc.
3rd — это база данных поддержки с другим отдельным менеджером транзакций.
Теперь проблема связана с удалением.
У меня есть следующий метод. @Transactional(«TransactionManager»)
private void deleteInTransaction(Instance instance) {
findById(instance.getId()).ifPresent(i ->delete(i));
}
Map<String, Object> jpaPropertiesMap = new HashMap<>();
jpaPropertiesMap.put(Environment.FORMAT_SQL, true);
jpaPropertiesMap.put(Environment.SHOW_SQL, true);
//TODO: renomear colunas no Entity e remover essa configuração.
jpaPropertiesMap.put("hibernate.globally_quoted_identifiers", true);
jpaPropertiesMap.put("hibernate.transaction.flush_before_completion" , true);
jpaPropertiesMap.put("hibernate.transaction.auto_close_session" , true);
jpaPropertiesMap.put("hibernate.current_session_context_class" , "thread" );
Spring Framework выдает следующий журнал.
2021-03-27 12:39:12 [http-nio-8080-exec-1] ОТЛАДКА o.h.e.t. внутренняя.TransactionImpl — begin 2021-03-27 12:39:12 [http-nio-8080-exec-1] ОТЛАДКА o.h.e.t. внутренняя.TransactionImpl — фиксация 2021-03-27 12:39:16 [http-nio-8080-exec-1] ОТЛАДКА o.h.e.t. внутренняя.TransactionImpl — begin 2021-03-27 12:39:16 [http-nio-8080-exec-1] ОТЛАДКА o.h.e.t. внутренняя.TransactionImpl — фиксация
и это не удаление (обратите внимание, что журнал отладки гибернации активирован.
Моя конфигурация диспетчера транзакций (основная)
@Qualifier(value="transactionManager")
@Primary
public PlatformTransactionManager transactionManager(
@Autowired EntityManagerFactory entityManagerFactory,
@Autowired DataSource dataSource) {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory);
txManager.setPersistenceUnitName("connemat");
txManager.setDataSource(dataSource);
txManager.setNestedTransactionAllowed(true);
return txManager;
}```
Any help will be very usefull.
Not that i know that i have deleteById and other features but this will not solve the issue.
Regards,
Contnuing the evaluation of the problem i created a property map to configure the session context.
I tried "thread" (which is the common sense) and the following error appear.
**2021-03-27 13:38:07 [http-nio-8080-exec-6] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is java.lang.IllegalStateException: Session/EntityManager is closed] with root cause
java.lang.IllegalStateException: Session/EntityManager is closed
at org.hibernate.internal.AbstractSharedSessionContract.checkOpen(AbstractSharedSessionContract.java:375)
at org.hibernate.engine.spi.SharedSessionContractImplementor.checkOpen(SharedSessionContractImplementor.java:149)
at org.hibernate.internal.SessionImpl.unwrap(SessionImpl.java:3666)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.orm.jpa.ExtendedEntityManagerCrea**
all options are throwing an error that the session is closed.
Hum, any reason why?
Комментарии:
1. Я нашел проблему. довольно странно.
2. объект с проблемой — это «много» в OneToMany с «многими нетерпеливыми». но набор <Entity> в other тоже был нетерпелив. было хорошо, потому что я исправил некоторые проблемы при настройке AbstractRoutingDataSource
3. к концу «N менеджеров транзакций» и N EntiyManagers не просто
4. хорошая статья. marcobehler.com/guides /…