4
@Service
@Repository
@Transactional
public class VideoService  {

    @PersistenceContext
    EntityManager entityManager;

    public void save(Video video) {

        Video video1 = new Video();

        entityManager.persist(video1);

    }



<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
    <persistence-unit name="video_pu" transaction-type="RESOURCE_LOCAL" >
        <provider>org.hibernate.ejb.HibernatePersistence</provider>

        <properties>
            <property name="hibernate.hbm2ddl.auto" value="create-drop" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
        </properties>

    </persistence-unit>
</persistence>


<bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/video" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>     

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="persistenceUnitName" value="video_pu"/>
      <property name="dataSource" ref="dataSource" />      
      <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
           <property name="showSql" value="true" />
           <property name="generateDdl" value="true" />
           <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" />
        </bean>
     </property>

    </bean>



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

    <!-- enable the configuration of transactional behavior based on annotations -->
    <tx:annotation-driven transaction-manager="transactionManager"/>


    <!-- post-processors for all standard config annotations -->
    <context:annotation-config/>

服务方法 save(Video video) 中的事务从未启动,因此也从未提交。错误在哪里?当我使用 EntityManagerFactory 时,它工作得很好,但我不想明确地开始和提交事务。我想将它与@Transactional 注释一起使用。

4

1 回答 1

3

@beerbajay 是正确的,@Transactional 将需要在您的 bean 上创建一个动态代理来应用事务逻辑,如果您的 Service 具有接口,则可以创建该代理,因为在您的情况下,它不是指示 Spring创建基于类的代理,方法如下:

<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class='true/>
于 2012-06-13T14:28:23.437 回答