У меня возникла проблема при ленивой загрузке. Это нормально работает с активной загрузкой. Ниже приведен код для applicationContext.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:p = "http://www.springframework.org/schema/p"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:jdbc = "http://www.springframework.org/schema/jdbc" xmlns:tx = "http://www.springframework.org/schema/tx"
xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<!-- Root Context: includes all context file -->
<import resource = "applicationContext-data.xml" />
<import resource = "applicationContext-service.xml" />
<import resource = "applicationContext-security-rest.xml" />
<import resource = "applicationContext-security-admin.xml" />
<import resource = "applicationContext-security-parent.xml" />
<import resource = "applicationContext-dozer.xml" />
<import resource = "batch/batch-launch-context.xml" />
<bean id = "appProperties"
class = "org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name = "locations">
<list>
<!-- Order matters, last one to create a property wins! -->
<value>classpath:application.properties</value>
<value>classpath:cron.properties</value>
</list>
</property>
<property name = "ignoreResourceNotFound" value = "false" />
</bean>
<bean id = "propertyConfigurer"
class = "org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
<property name = "properties" ref = "appProperties" />
</bean>
<!-- Quartz scheduler details -->
</beans>
Ниже приведен код для applicationContext-data.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns:p = "http://www.springframework.org/schema/p"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:jpa = "http://www.springframework.org/schema/data/jpa" xmlns:jdbc = "http://www.springframework.org/schema/jdbc"
xmlns:tx = "http://www.springframework.org/schema/tx" xmlns:util = "http://www.springframework.org/schema/util"
xsi:schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<jpa:repositories base-package = "com.tappingpotentials.sms"
repository-impl-postfix = "CustomImpl" />
<bean id = "dataSource" class = "org.springframework.jndi.JndiObjectFactoryBean">
<property name = "jndiName" value = "jdbc/tpSMSDS" />
<property name = "resourceRef" value = "true" />
</bean>
<bean id = "taskExecutor" class = "org.springframework.core.task.SimpleAsyncTaskExecutor" />
<bean id = "transactionManager" class = "org.springframework.orm.jpa.JpaTransactionManager">
<property name = "entityManagerFactory" ref = "entityManagerFactory" />
</bean>
<tx:annotation-driven />
<bean id = "entityManagerFactory"
class = "org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name = "dataSource" ref = "dataSource" />
<property name = "packagesToScan" value = "com.tappingpotentials.sms" />
<property name = "jpaVendorAdapter">
<bean id = "jpaAdapter"
class = "org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name = "database" value = "MYSQL" />
<property name = "showSql" value = "false" />
<property name = "generateDdl" value = "true" />
</bean>
</property>
<property name = "jpaProperties">
<props>
<prop key = "hibernate.listeners.envers.autoRegister">false</prop>
<prop key = "hibernate.hbm2ddl.auto">update</prop>
<!-- <prop key = "hibernate.connection.provider_class"> org.hibernate.c3p0.internal.C3P0ConnectionProvider
</prop> -->
<prop key = "hibernate.c3p0.min_size">
1
</prop>
<prop key = "hibernate.c3p0.max_size">
19
</prop>
<prop key = "hibernate.c3p0.timeout">
120
</prop>
<prop key = "hibernate.c3p0.max_statements">
10
</prop>
</props>
</property>
</bean>
</beans>
Я все перепробовал. Я думаю, что транзакционная аннотация не работает. Я использовал аннотацию @Transactional в своем классе обслуживания для метода. Вот мой класс обслуживания
@Override
@Transactional
public SchoolSessionDetail saveSchoolSession(SchoolSessionDetail sessionDetail) {
List<SmsSchoolSession> sessions = smsSchoolSessionRepository.findBySmsSchool_IdOrderByStartDateDesc(loggedInSchool().getId());
sessions.forEach(session->{
if (session.getIsCurrent() == (byte)1) {
session.setIsCurrent((byte)0);
saveStudentArchive(session.getSmsClassroom(), session.getSmsStudentArchives());
}
});
SmsSchoolSession session = createNewSchoolSession(sessionDetail);
sessions.add(session);
if (smsSchoolSessionRepository.save(sessions) != null) {
SmsSchoolSession currentSession = smsSchoolSessionRepository.findByIsCurrentAndSmsSchool((byte)1, loggedInSchool());
updateSchoolSession(currentSession);
return new SchoolSessionDetail(currentSession);
}
return null;
}
Пожалуйста, предложите мне решение для этого.
Вставьте всю трассировку стека!





Я предполагаю, что вам понадобится Hibernate.initialize(session.getSmsStudentArchives()) прямо перед доступом к ленивым дочерним элементам.
Но это привело бы к дополнительному запросу для каждого сеанса. Вы можете использовать NamedEntityGraph для уменьшения доступа к базе данных:
@NamedEntityGraph(
name = "smsSchoolSessionWithStudentArchives",
attributeNodes = { @NamedAttributeNode("smsStudentArchives") })
public class SmsSchoolSession {
@EntityGraph("smsSchoolSessionWithStudentArchives")
List<SmsSchoolSession> findBySmsSchool_IdOrderByStartDateDesc(whatever id);
При этом все элементы сеанса будут иметь элементы архива, доступные без использования Hibernate.initialize.
тогда это может быть другое поле. Добавьте трассировку стека, как уже отмечалось.
Это исключение возникло в вашей службе? Ясно, что этого не должно происходить, если транзакция активна. Какая строка вызывает исключение. Добавьте трассировку стека.