最近我在我的应用程序中配置了第二个数据库连接,一切都运行良好,直到我试图从一个实体(IncomeTariff)获取延迟初始化的集合。我有两个独立的数据源,实体管理器等。重要的是LazyInitializationException仅在我从新添加的数据库中获取实体时才会发生。更重要的是,当我使用IncomeTariff将表移动到旧数据库时,我能够毫无问题地获得此集合。我尝试了很多东西:添加@Transactional,使用Hibernate.initialize()等等。在日志中,看起来hibernate过早关闭会话并且我无法让它工作。我希望代码片段能够使这一点更清晰。
数据源配置:
<!-- data source 1 -->
<bean id="dataSource1" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">
<property name="driverClassName" value="${mysql.jdbc.driver}" />
<property name="url" value="${mysql.jdbc.uri}" />
<property name="username" value="${mysql.jdbc.username}" />
<property name="password" value="${mysql.jdbc.password}" />
<property name="maxActive" value="${mysql.jdbc.maxActive}" />
<property name="testOnBorrow" value="true" />
<property name="testOnReturn" value="true" />
<property name="testWhileIdle" value="true" />
<property name="timeBetweenEvictionRunsMillis" value="30000" />
<property name="validationQuery" value="select 1" />
<property name="validationInterval" value="30000" />
<property name="jdbcInterceptors"
value="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer" />
<property name="jmxEnabled" value="true" />
<property name="logAbandoned" value="true" />
<property name="maxWait" value="10000" />
<property name="minEvictableIdleTimeMillis" value="30000" />
<property name="removeAbandoned" value="true" />
<property name="removeAbandonedTimeout" value="1200" />
</bean>
<bean id="defaultJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"
p:dataSource-ref="dataSource1" primary="true" />
<bean id="defaultNamedParameterJdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource1" />
</bean>
<!-- data source 2 -->
<bean id="dataSource2" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">
<property name="driverClassName" value="${mysql.jdbc.driver}" />
<property name="url" value="${mysql.ds2.uri}" />
<property name="username" value="${mysql.ds2.username}" />
<property name="password" value="${mysql.ds2.password}" />
<property name="maxActive" value="${mysql.jdbc.maxActive}" />
<property name="testOnBorrow" value="true" />
<property name="testOnReturn" value="true" />
<property name="testWhileIdle" value="true" />
<property name="timeBetweenEvictionRunsMillis" value="30000" />
<property name="validationQuery" value="select 1" />
<property name="validationInterval" value="30000" />
<property name="jdbcInterceptors"
value="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer" />
<property name="jmxEnabled" value="true" />
<property name="logAbandoned" value="true" />
<property name="maxWait" value="10000" />
<property name="minEvictableIdleTimeMillis" value="30000" />
<property name="removeAbandoned" value="true" />
<property name="removeAbandonedTimeout" value="1200" />
</bean>
旧DB的JPA配置:
@Configuration
@EnableJpaRepositories(basePackages = { "pl.application.first.repository"})
@EnableTransactionManagement
public class JpaConfig {
@Autowired
@Qualifier("dataSource1")
private DataSource dataSource;
@Bean
@Primary
public EntityManagerFactory entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(false);
vendorAdapter.setShowSql(false);
vendorAdapter.setDatabasePlatform("MYSQL");
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setPersistenceUnitName("unit1");
factoryBean.setJpaProperties(prepareProperties());
factoryBean.afterPropertiesSet();
return factoryBean.getObject();
}
@Bean
@Primary
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
private Properties prepareProperties() {
Properties prop = new Properties();
prop.put("hibernate.cache.use_second_level_cache", true);
prop.put("hibernate.cache.use_query_cache", false);
prop.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory");
prop.put("hibernate.cache.provider_class", "org.hibernate.cache.SingletonEhCacheProvider");
prop.put("javax.persistence.validation.mode", "none");
return prop;
}
}
新DB的JPA配置:
@Configuration
@EnableJpaRepositories(basePackages = {
"pl.application.second.repository" }, entityManagerFactoryRef = "secondEntityManagerFactory", transactionManagerRef = "secondTransactionManager")
@EnableTransactionManagement
public class NewJpaConfig {
@Autowired
@Qualifier("dataSource2")
private DataSource dataSource;
@Bean(name = "secondEntityManagerFactory")
public EntityManagerFactory entityManagerFactory() {
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(false);
vendorAdapter.setShowSql(true);
vendorAdapter.setDatabasePlatform("MYSQL");
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(dataSource);
factoryBean.setJpaProperties(prepareProperties());
factoryBean.setPackagesToScan("pl.application.operator", "pl.application.common.db.converters");
factoryBean.setPersistenceUnitName("unit2");
factoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
factoryBean.afterPropertiesSet();
return factoryBean.getObject();
}
@Bean(name = "secondTransactionManager")
public PlatformTransactionManager transactionManager() {
JpaTransactionManager txManager = new JpaTransactionManager();
txManager.setEntityManagerFactory(entityManagerFactory());
return txManager;
}
private Properties prepareProperties() {
Properties prop = new Properties();
prop.put("hibernate.cache.use_second_level_cache", true);
prop.put("hibernate.cache.use_query_cache", false);
prop.put("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory");
prop.put("hibernate.cache.provider_class", "org.hibernate.cache.SingletonEhCacheProvider");
prop.put("javax.persistence.validation.mode", "none");
prop.put("hibernate.connection.autocommit", "false");
prop.put("javax.persistence.lock.timeout", "90000");
return prop;
}
}
导致问题的IncomeTariff类:
@Entity
@Table(name = "income_tariff")
public class IncomeTariff extends Entity {
@OneToMany(mappedBy = "incomeTariff")
private List<IncomeTariffEntry> incomeTariffEntries;
public List<IncomeTariffEntry> getIncomeTariffEntries() {
return incomeTariffEntries;
}
public void setIncomeTariffEntries(List<IncomeTariffEntry> incomeTariffEntries) {
this.incomeTariffEntries = incomeTariffEntries;
}
@Override
public int hashCode() {
int hash = 7;
hash = 23 * hash + Objects.hashCode(this.getId());
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final IncomeTariff other = (IncomeTariff) obj;
if (!Objects.equals(this.getId(), other.getId())) {
return false;
}
return true;
}
}
来自旧数据库的BillingAccount实体类,工作正常:
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type", discriminatorType = DiscriminatorType.STRING)
@Table(name = "api_billing_account")
public class BillingAccount extends Entity {
@OneToMany(mappedBy = "billingAccount")
private List<User> users = new ArrayList<>();
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
和IncomeTariffService一样,你现在可以看到方法findAllTariffs()没有任何意义,我修改它只是为了表明从BillingAccount中获取用户工作正常。存储库只是基于Spring数据的常规存储库:
@Service
@Transactional
public class IncomeTariffService {
@Autowired
private final IncomeTariffRepository incomeTariffRepository; // fetching data from new DB
@Autowired
private BillingAccountRepository billingAccountRepository; //fetching data from old DB
private static final Logger logger = LoggerFactory.getLogger(IncomeTariffService.class);
public List<IncomeTariff> findAllTariffs() {
BillingAccount findOne = billingAccountRepository.findOne(666000);
logger.info("TEST");
logger.info("" + findOne.getUsers().size());
return null;
}
public List<IncomeTariffEntry> findPositions(Integer tariffId) {
IncomeTariff findOne = incomeTariffRepository.findOne(tariffId);
logger.info("TEST");
List<IncomeTariffEntry> incomeTariffEntries = findOne.getIncomeTariffEntries();
logger.info("" + incomeTariffEntries.size());
return incomeTariffEntries;
}
}
此处,当我从结算帐户中提取用户列表时,日志中发生了什么:
11:33:48.988 [http-nio-8080-exec-33] TRACE org.hibernate.type.CollectionType - Created collection wrapper: [pl.application.billing.model.BillingAccount.users#666000]
11:33:48.989 [http-nio-8080-exec-33] INFO p.s.a.c.t.s.IncomeTariffService - TEST
11:33:48.990 [http-nio-8080-exec-33] TRACE o.h.type.descriptor.sql.BasicBinder - binding parameter [1] as [INTEGER] - [666000]
11:33:48.997 [http-nio-8080-exec-33] INFO p.s.a.c.t.s.IncomeTariffService - 0
11:33:48.997 [http-nio-8080-exec-33] DEBUG o.s.orm.jpa.JpaTransactionManager - Initiating transaction commit
11:33:48.997 [http-nio-8080-exec-33] DEBUG o.s.orm.jpa.JpaTransactionManager - Committing JPA transaction on EntityManager [org.hibernate.jpa.internal.EntityManagerImpl@72eaf768]
11:33:48.999 [http-nio-8080-exec-33] DEBUG o.s.orm.jpa.JpaTransactionManager - Not closing pre-bound JPA EntityManager after transaction
11:33:49.001 [http-nio-8080-exec-33] DEBUG o.s.o.j.s.OpenEntityManagerInViewFilter - Closing JPA EntityManager in OpenEntityManagerInViewFilter
11:33:49.001 [http-nio-8080-exec-33] DEBUG o.s.o.jpa.EntityManagerFactoryUtils - Closing JPA EntityManager
我能够获得用户集合大小,看起来事务在方法结束时关闭
以下是我获取IncomeTariff(没有@Transactional注释)时发生的事情:
13:09:31.285 [http-nio-8080-exec-51] TRACE org.hibernate.type.CollectionType - Created collection wrapper: [pl.application.operator.pricelist.income.IncomeTariff.incomeTariffEntries#1]
13:09:31.288 [http-nio-8080-exec-51] DEBUG o.s.orm.jpa.JpaTransactionManager - Initiating transaction commit
13:09:31.288 [http-nio-8080-exec-51] DEBUG o.s.orm.jpa.JpaTransactionManager - Committing JPA transaction on EntityManager [org.hibernate.jpa.internal.EntityManagerImpl@427c27e2]
13:09:31.316 [http-nio-8080-exec-51] DEBUG o.s.orm.jpa.JpaTransactionManager - Closing JPA EntityManager [org.hibernate.jpa.internal.EntityManagerImpl@427c27e2] after transaction
13:09:31.317 [http-nio-8080-exec-51] DEBUG o.s.o.jpa.EntityManagerFactoryUtils - Closing JPA EntityManager
13:09:31.317 [http-nio-8080-exec-51] INFO p.s.a.c.t.s.IncomeTariffService - TEST
13:09:31.342 [http-nio-8080-exec-51] ERROR p.s.a.r.c.e.GlobalExceptionHandler - failed to lazily initialize a collection of role: pl.application.operator.pricelist.income.IncomeTariff.incomeTariffEntries, could not initialize proxy - no Session
并使用@Transactional注释:
12:24:14.599 [http-nio-8080-exec-42] TRACE org.hibernate.type.CollectionType - Created collection wrapper: [pl.application.operator.pricelist.income.IncomeTariff.incomeTariffEntries#1]
12:24:14.600 [http-nio-8080-exec-42] DEBUG o.s.orm.jpa.JpaTransactionManager - Initiating transaction commit
12:24:14.600 [http-nio-8080-exec-42] DEBUG o.s.orm.jpa.JpaTransactionManager - Committing JPA transaction on EntityManager [org.hibernate.jpa.internal.EntityManagerImpl@4b5b7e77]
12:24:14.601 [http-nio-8080-exec-42] DEBUG o.s.orm.jpa.JpaTransactionManager - Closing JPA EntityManager [org.hibernate.jpa.internal.EntityManagerImpl@4b5b7e77] after transaction
12:24:14.601 [http-nio-8080-exec-42] DEBUG o.s.o.jpa.EntityManagerFactoryUtils - Closing JPA EntityManager
12:24:14.601 [http-nio-8080-exec-42] DEBUG o.s.orm.jpa.JpaTransactionManager - Resuming suspended transaction after completion of inner transaction
12:24:14.601 [http-nio-8080-exec-42] INFO p.s.a.c.t.s.IncomeTariffService - TEST
12:24:14.604 [http-nio-8080-exec-42] DEBUG o.s.orm.jpa.JpaTransactionManager - Initiating transaction rollback
12:24:14.604 [http-nio-8080-exec-42] DEBUG o.s.orm.jpa.JpaTransactionManager - Rolling back JPA transaction on EntityManager [org.hibernate.jpa.internal.EntityManagerImpl@5e7c4044]
12:24:14.606 [http-nio-8080-exec-42] DEBUG o.s.orm.jpa.JpaTransactionManager - Not closing pre-bound JPA EntityManager after transaction
12:24:14.612 [http-nio-8080-exec-42] ERROR p.s.a.r.c.e.GlobalExceptionHandler - failed to lazily initialize a collection of role: pl.application.operator.pricelist.income.IncomeTariff.incomeTariffEntries, could not initialize proxy - no Session
交易在&#34; TEST&#34;之前关闭甚至被记录,然后从实体获取集合是不可能的。正如我之前提到的,当我将income_tariff移动到旧数据库时,一切都正常工作,所以我的配置可能有问题,但我现在已经挣扎了两天而且我没有想法。< / p>