HibernateException:无法获取当前线程的事务同步会话。

时间:2016-09-10 11:04:56

标签: hibernate spring-mvc h2 dao applicationcontext

我是spring,hibernate和数据库的新手。我得到" HibernateException:无法获取当前线程的事务同步会话"错误。 请帮我。在下面找到代码。

这是控制器

@Controller
public class ProductController {
@Autowired
private ProductService productService ; 
@RequestMapping("/productTable")
public ModelAndView getProducts(Map<String, Object> map){
    Product product = new Product();
    map.put("product", product);
    map.put("productList", productService.getAllProduct());
    ModelAndView modelandview = new ModelAndView("ProductTable");
    return modelandview ;
}
@RequestMapping(value="/product.do" , method=RequestMethod.POST)
public String doActions(@ModelAttribute Product product,BindingResult           result,@RequestParam String action,Map<String, Object> map){
    Product productResult = new Product();

    if(action.toLowerCase()=="add"){
        productService.addProduct(product);
        productResult = product ;
    }
    else if(action.toLowerCase()=="edit"){
        productService.editProduct(product);
        productResult = product ;   
    }
    else if(action.toLowerCase()=="delete"){
        productService.deleteProduct(product.getProductId());
        productResult = new Product() ; 
    }

    else if(action.toLowerCase()=="search"){
        Product searchedProduct =   productService.getProduct(product.getProductId());
        productResult = searchedProduct !=null ? searchedProduct : new     Product();
    }
    else{
    }

    map.put("product", product);
    map.put("productList", productService.getAllProduct());
    return "Product" ;
}

这是EntityDaoImplementation

@Transactional
@Repository
public class ProductDaoImpl implements ProductDao{
@Autowired
private SessionFactory session ;
public void addProduct(Product product) {
    session.getCurrentSession().save(product);  
}
public void editProduct(Product product) {
    session.getCurrentSession().update(product);    
}
public void deleteProduct(int productId) {
    session.getCurrentSession().delete(getProduct(productId));  
}
public Product getProduct(int productId) {
    return session.getCurrentSession().get(Product.class,productId);
}
public List<Product> getAllProduct() {  
    return session.getCurrentSession().createQuery("from Product").list();
}

}

这是我的Model类

@Entity
@Table(name="PRODUCT")
public class Product {
@Id
@Column(name="PRODUCTID")
@GeneratedValue(strategy=GenerationType.AUTO)
private int productId ;
@Column(name="PRODUCTNAME")
private String productName;
@Column(name="PRODUCTCATEGORY")
private String productCategory ;
@Column(name="PRICE")
private float price ;
//getter-setter and constructor
}

这是serviceImplemetation

@Service
public class ProductServiceImpl implements ProductService{
@Autowired
private ProductDao productDao;

public void addProduct(Product product) {
    productDao.addProduct(product);
}

public void editProduct(Product product) {
    productDao.editProduct(product);    
}

public void deleteProduct(int productId) {
    productDao.deleteProduct(productId);    
}

public Product getProduct(int productId) {  
    return productDao.getProduct(productId);
}

public List<Product> getAllProduct() {
    return productDao.getAllProduct();
}
}

这是ProductTable.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"       pageEncoding="ISO-8859-1"%>
  <%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
  <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
  <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
  <%@ include file="Common-Header.jsp"%>
  <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"         "http://www.w3.org/TR/html4/loose.dtd">
   <html>
   <head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Product Management</title>
</head>

<body>
<h1>Product Data</h1>
<form:form action="product.do" method="POST" commandName="product">
<table>
    <tr>
        <td>Product Id</td>
        <td><form:input path="productId"  /></td>
    </tr>
    <tr>
        <td>Product Name</td>
        <td><form:input path="productName"  /></td>
    </tr>
    <tr>
        <td>Product Category</td>
        <td><form:input path="productCategory"  /></td>
     </tr>
     <tr>
        <td>Price</td>
        <td><form:input path="price"  /></td>
     </tr>
     <tr>
        <td colspan="2">
            <input type="submit" name="action" value="Add" />
            <input type="submit" name="action" value="Edit" />
            <input type="submit" name="action" value="Delete" />
            <input type="submit" name="action" value="Search" />
        </td>
    </tr>
   </table>
   </form:form>
   <br>
   <table border="1">
   <th>Product Id</th>
   <th>Product Name</th>
   <th>Product Category</th>
   <th>Price</th>
   <c:forEach items="${productList}" var="product">
    <tr>
        <td>${product.productId}</td>
        <td>${product.productName}</td>
        <td>${product.productCategory}</td>
        <td>${product.price}</td>
    </tr>
 </c:forEach>
 </table>
 </body>
 </html>

这是web.xml

<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Archetype Created Web Application</display-name>
<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-      class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/dispatcher-servlet.xml,
                /WEB-INF/applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-  class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<listener>
    <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>

这是Dispatcher servlet

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

  <mvc:annotation-driven />
  <mvc:resources mapping="/css/**" location="/resources/css/" />
  <mvc:resources mapping="/images/**" location="/resources/images/" /> 
  <mvc:resources mapping="/resources/**" location="/resources/" />
 <context:component-scan base-package="com.quickart" />

 <bean id="viewResolver"
            class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
</bean>

</beans>

这是ApplicationContext.xml

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

<!-- Enable autowire -->
<context:annotation-config />
<context:component-scan base-package="com.quickart" />
<mvc:annotation-driven /> 
<mvc:resources mapping="/resources/**" location="/resources/" />

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.h2.Driver" />
    <property name="url" value="jdbc:h2:tcp://localhost/~/testRakesh" />
    <property name="username" value="sa" />
    <property name="password" value="" />
</bean>

<!-- Session Factory Declaration -->
<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="com.quickart" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.enable_lazy_load_no_trans">true</prop>
            <!-- <prop key="hibernate.default_schema">test</prop> -->
            <prop key="format_sql">true</prop>
            <prop key="use_sql_comments">true</prop>
            <!-- <prop key="hibernate.hbm2ddl.auto">create</prop> -->
        </props>
    </property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
 <bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

请帮忙!谢谢。

2 个答案:

答案 0 :(得分:1)

我知道回答已经很晚了。我也面临着这种类型的问题,当我用@Transaction注释我的方法时,它对我起作用了,即



    @Transactional
    @Repository
    public class ProductDaoImpl implements ProductDao{
    @Autowired
    private SessionFactory session ;

    @Transactional
    public void addProduct(Product product) {
        session.getCurrentSession().save(product);  
    }

    @Transactional
    public void editProduct(Product product) {
        session.getCurrentSession().update(product);    
    }

    @Transactional
    public void deleteProduct(int productId) {
        session.getCurrentSession().delete(getProduct(productId));  
    }

    @Transactional
    public Product getProduct(int productId) {
        return session.getCurrentSession().get(Product.class,productId);
    }

    @Transactional
    public List getAllProduct() {  
        return session.getCurrentSession().createQuery("from Product").list();
    }

    }


答案 1 :(得分:0)

也许是因为在你的web.xml中你加载了servlet中的两个上下文。它们都扫描相同的包,但是您的调度程序servlet没有事务管理器(并且首先加载somaybe,因为ProductServiceImpl没有加载事务代理)。我会尝试:

在调度程序servlet中,仅使用包含过滤器扫描带注释的@Controller类。

在应用程序上下文中,使用排除过滤器扫描@Controller类以外的所有内容。

<context:component-scan base-package="org.quickart">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
     </context:component-scan>