JpaTransactionManager 中未正确设置事务边界

Transaction boundary is not properly set in JpaTransactionManager

我正在使用 JPA 和 Hibernate 实现并使用 JpaTransactionManager 来管理事务。

下面是我的应用程序上下文文件

<bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
    <property name="persistenceXmlLocations">
        <list>
            <value>classpath*:META-INF/persistence.xml</value>
        </list>
    </property>
    <property name="defaultDataSource" ref="dataSource" />
</bean>

<bean id="entityManagerFactory" primary="true"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitManager" ref="persistenceUnitManager" />
    <property name="persistenceUnitName" value="infra_services" />
</bean>

<bean
    class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

<tx:annotation-driven transaction-manager="transactionManager"
    proxy-target-class="true" />

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
    <property name="jpaDialect">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
    </property>
</bean>

我已将我的服务 class 定义如下

@Service
@Transactional
public class ComponentService {

我在dao层执行如下查询

Query q = entityManager.createQuery(
            "SELECT cc.component FROM "
                    + this.typeParameterClass.getSimpleName()
                    + " cc WHERE cc.caseload.id = ? ").setParameter(1,
            caseloadId);

    Collection<Component> ddd =q.getResultList();
    for (Component c : ddd) {
        System.out.println(c.getComponentId());
        System.out.println(c.getComponentRelationships2());
    }
    return ddd;

我从 select 查询开始。执行行 System.out.println(c.getComponentRelationships2()); 时得到 could not initialize proxy - no Session] with root cause 异常

不确定为什么会话在这里不可用。请帮我解决这个问题。

如果您的服务与 <tx:annotation-driven /> 所在的服务不在同一上下文中,则它无法正常工作。因为它只在相同的上下文中寻找 bean。摘自 spring 文档:

@EnableTransactionManagement and only looks for @Transactional on beans in the same application context they are defined in. This means that, if you put annotation driven configuration in a WebApplicationContext for a DispatcherServlet, it only checks for @Transactional beans in your controllers, and not your services. See Section 21.2, “The DispatcherServlet” for more information.