@Transactional注释不起作用.数据库行未创建

ris*_*p89 1 spring jpa spring-mvc transactional

以下是我的所有代码.未创建数据库行.没有异常抛出.

package com.rishi.app.models;

import java.util.Collection;

import javax.management.Query;
import javax.persistence.Entity;
import javax.persistence.EntityManager;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceUnit;
import javax.persistence.TypedQuery;

@Entity
public class Customer {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String firstName;
    private String lastName;

    protected Customer() {}

    public Customer(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[id=%d, firstName='%s', lastName='%s']",
                id, firstName, lastName);
    }

}


package com.rishi.app.repositories;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

import org.springframework.stereotype.Repository;

import com.rishi.app.models.Customer;

@Repository
public class CustomerRepository {
    @PersistenceContext
    private EntityManager em;

    @Transactional
    public void save(Customer c) {
        em.persist(c);
    }
}

package com.rishi.app.controllers;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.rishi.app.models.Customer;
import com.rishi.app.repositories.CustomerRepository;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
    @PersistenceContext
    EntityManager entityManager;


    @Autowired
    EntityManagerFactory entityManagerFactory;

    @Autowired
    CustomerRepository customerRepository;

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    /**
     * Simply selects the home view to render by returning its name.
     * @throws Exception 
     */
    @Transactional
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String home(Locale locale, Model model) {
        logger.info("Welcome home controller! The client locale is {}.", locale);

        Customer c = new Customer("Rishi", "Paranjape");
        customerRepository.save(c);

            //Following 4 lines work just fine. Database row is actually created.
        //EntityManager em = entityManagerFactory.createEntityManager();
        //em.getTransaction().begin();
        //em.persist(c);
        //em.getTransaction().commit();

        Date date = new Date();
        DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);

        String formattedDate = dateFormat.format(date);

        model.addAttribute("serverTime", formattedDate );
        //throw new Exception("bad stuff");
        return "home";
    }

}
Run Code Online (Sandbox Code Playgroud)

我的servlet上下文xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->

    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />

    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
    <resources mapping="/resources/**" location="/resources/" />

    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="prefix" value="/WEB-INF/views/" />
        <beans:property name="suffix" value=".jsp" />
    </beans:bean>

    <context:component-scan base-package="com.rishi.app" />


    <beans:bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <beans:property name="dataSource" ref="dataSource" />
      <beans:property name="packagesToScan" value="com.rishi.app.models" />
      <beans:property name="jpaVendorAdapter">
         <beans:bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
      </beans:property>
      <beans:property name="jpaProperties">
         <beans:props>
            <beans:prop key="hibernate.hbm2ddl.auto">validate</beans:prop>
            <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</beans:prop>
         </beans:props>
      </beans:property>
   </beans:bean>

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

    <beans:bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
      <beans:property name="entityManagerFactory" ref="entityManagerFactory" />
   </beans:bean>
   <tx:annotation-driven mode="aspectj" transaction-manager="transactionManager" />


</beans:beans>
Run Code Online (Sandbox Code Playgroud)

我有根上下文和servlet上下文.我的所有bean都在servlet上下文中(我的根上下文几乎为空).我的主要问题是em.persist()被调用但什么也没做.如果我调试应用程序,我可以看到来自CustomerRepository的save方法被调用.没有任何异常抛出或错误显示.但是,没有创建数据库行.

Ang*_*ity 6

可能的原因是@Transactional在错误的春季环境中应用于bean.

许多Spring MVC应用程序有两个上下文:一个根上下文通常用于公共bean,例如事务服务/存储库,以及一个特定于Web的上下文,其中包含控制器,请参阅此答案以获取更多详细信息.

似乎正在发生的是tx:annotation-driven应用于控制器或存储库都不存在的上下文.

它看起来像是@Transactional应用于根上下文,并将所有bean放在调度程序上下文中.

如果是这种情况,请tx:annotation-driven转到定义bean的XML文件或相应的文件component-scan.这将适用@Transactional于豆类肯定的上下文.

通常作为一般的最佳实践,我们@Transactional不应用于控制器,也不应用于存储库,而是应用于@Service包含业务逻辑的中间服务层bean .

但是存储库和控制器只是春天的bean,所以如果你想使用@transactional它也可以.