Spring boot @Transactional

2019-05-14 09:19发布

问题:

Does spring boot automatically add @Transactional annotation at controller layer? I tried putting @Transactional at service layer but it seems that the controller layer is overriding the annotation.

I have this config

<tx:advice id="txAdvice" transaction-manager="transactionManager">
    <tx:attributes>
        <tx:method name="find*" read-only="true" isolation="READ_COMMITTED"
            propagation="NOT_SUPPORTED" />
        <tx:method name="load*" read-only="true" isolation="READ_COMMITTED"
            propagation="NOT_SUPPORTED" />
        <tx:method name="get*" read-only="true" isolation="READ_COMMITTED"
            propagation="NOT_SUPPORTED" />
        <tx:method name="*" timeout="30" propagation="REQUIRED" />
    </tx:attributes>
</tx:advice>

<aop:config proxy-target-class="true">
    <aop:advisor advice-ref="txAdvice"
        pointcut="execution(* *..service.*Service*.*(..))" order="1" />
</aop:config>

and even If I remove that config the transaction still works.

EDIT:

here's my datasource config

<bean id="msDataSource" class="org.apache.tomcat.jdbc.pool.DataSource"
    destroy-method="close">
    <property name="driverClassName" value="${jdbc.main.driverClass}" />
    <property name="url" value="${jdbc.main.url}" />
    <property name="username" value="${jdbc.main.username}" />
    <property name="password" value="${jdbc.main.password}" />

</bean>


<bean id="msPUM"
    class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
    <property name="defaultDataSource" ref="msDataSource" />
</bean>

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="persistenceUnitManager" ref="msPUM" />
    <!--<property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> 
        <property name="database" value="ORACLE"/> <property name="generateDdl" value="false"/> 
        <property name="showSql" value="true" /> </bean> </property> -->
</bean>

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

回答1:

I'm just guessing but I assume what you're trying to ask here is why you're able to load lazy collections on your entities inside your controller?

Spring Boot configures the following application property spring.jpa.open-in-view with a default value of "true". Basically this opens a session for the entire request allowing you to do things like the above outside of a @Transactional.

Adding this to your application.properties will turn it off:

spring.jpa.open-in-view=false