以下是我的所有代码。未创建数据库行。没有例外。
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";
}
}
我的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>
我有根上下文和servlet上下文。我的所有bean都在servlet上下文中(我的根上下文几乎为空)。我的主要问题是em.persist()被调用但什么也没做。如果我调试应用程序,我可以看到来自CustomerRepository的save方法被调用。没有任何异常抛出或错误显示。但是,没有创建数据库行。
答案 0 :(得分:6)
可能的原因是@Transactional
在错误的spring上下文中应用于bean。
许多Spring MVC应用程序有两个上下文:一个根上下文通常用于公共bean,例如事务服务/存储库,以及一个特定于Web的上下文,其中包含控制器,有关详细信息,请参阅此answer。 p>
似乎正在发生的事情是tx:annotation-driven
正在应用于控制器或存储库都不存在的上下文。
看起来@Transactional
应用于根上下文,并将所有bean放在调度程序上下文中。
如果是这种情况,请将tx:annotation-driven
移动到定义了bean的XML文件或相应的component-scan
。这将在bean确定的上下文中应用@Transactional
。
通常作为一般的最佳实践,我们不在控制器上应用@Transactional
,也不在存储库中,而是在包含业务逻辑的@Service
注释的中间服务层bean中。
但是存储库和控制器只是春天的bean,所以如果你想使用@transactional
也可以。
答案 1 :(得分:4)
您正在使用javax.transaction.Transactional
,而您应该使用org.springframework.transaction.annotation.Transactional
。
答案 2 :(得分:2)
首先为您的存储库编写集成测试。缩小问题是否在您的控制器或存储库中将更容易缩小范围。
理论上,您的@Transactional
存储库save()
方法不在接口中,因此除非您向{proxy-target-class=true
添加<tx:annotation-driven>
,否则不会为其创建JDK动态代理。 1}}元素并将CGLIB添加到类路径中。如果未创建代理,则不建议执行事务性工作。您可以通过在存储库中设置断点并查看堆栈帧来查看是否提及TransactionInterceptor
类。
实际上,如果缺少事务代理,我希望得到一个例外,你没有开放会话(至少在Hibernate中)。因为你没有得到异常,我怀疑Spring是装饰您的控制器的@Transactional
并且这不是交易问题。
要测试它是否是事务性问题,请在保存后调用flush()
,在刷新之后但在事务关闭之前设置断点,并在其他地方(集成测试,数据库控制台,无论如何)创建一个READ_UNCOMMITTED
隔离的新事务,并检查是否可以读取(请参阅)该行。
答案 3 :(得分:0)
删除mode=aspectj
,因为如果没有JVM代理和<context:load-time-weaver/>
这不起作用(另请参阅此answer)。
删除它将允许Spring使用非aspectj编织机制(如果适用,则使用JDK代理或CGLIB代理),因此@Transactional
应该可以处理servlet上下文中的任何bean。