springMVC之事务配置(问题来源:为什么数据保存不了)

一 问题来源

自己的亲身体会,来源问题this.sessionFactory.getCurrentSession().save(obj);保存不了数据。

二、解决方法

原因在springMVC配置事务时,事务注解应该在类扫描注解之后,然后在到相对应dao层的方法要加@Transaction

全注解配置如下:

第一步,首先看一下web.xml,如下:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:web="http://java.sun.com/xml/ns/javaee" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
        id="WebApp_ID" version="3.0">
  <display-name>Archetype Created Web Application</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/spring-*.xml</param-value>
  </context-param>
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <servlet>
    <servlet-name>lei-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:/lei-dispatcher-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>lei-dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

  

第二步,spring-hibernate配置,见以下spring-hibernate.xml配置

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"  
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="  
         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/aop http://www.springframework.org/schema/aop/spring-aop-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> 
<!-- 配置数据源 -->	
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
		<property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8"/>
		<property name="username" value="root"/>
		<property name="password" value="root"/>
	</bean>
	
<!-- 配置sessionFactory-->
	<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<property name="dataSource" ref="dataSource"/>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
				<prop key="hibernate.hbm2ddl.auto">update</prop> 
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hiberante.format_sql">true</prop>
                <prop key="current_session_context_class">thread</prop>
			</props>
		</property>
		<property name="configLocations">
			<list>
				<value>
					classpath*:hibernate.cfg.test.xml
				</value>
			</list>
		</property>
	</bean>
	
	<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	

</beans>

  第三步:springMVC配置

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

	<!-- 注解扫描包 -->
	<context:component-scan base-package="com.example.*"/>
	
	
	 <tx:annotation-driven transaction-manager="transactionManager"/>
	
	<!-- 引入注解类      
		下面两个都可以注释
	 -->
	<mvc:annotation-driven/>
<!-- 	<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> -->
	
<!-- 	<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" /> -->
	
	<!-- 文件上传配置 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		  <property name="defaultEncoding" value="utf-8" />
	      <property name="maxUploadSize" value="10485760000" />
	      <property name="maxInMemorySize" value="40960" />
	</bean>
	

	<!-- 静态资源访问配置 -->
	<mvc:resources location="/img/" mapping="/img/**"/>
	<mvc:resources location="/topui/" mapping="/topui/**"/>
	<!-- 视图解析器 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
 </beans>  

  到这配置完毕,相对应的dao层如下:

package com.example.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.example.dao.IFilesDAO;
import com.example.entity.Files;

@Repository
public class FilesDAO implements IFilesDAO{

	@Resource
	private SessionFactory sessionFactory;

	@SuppressWarnings("unchecked")
	@Override
	public List<Files> findFilesList(String id) {
		// TODO Auto-generated method stub
		return this.sessionFactory.getCurrentSession().createQuery("from Files where id='" + id+"'").list();
	}

	@Transactional
	@Override
	public void deleteFile(Files file) {
		this.sessionFactory.getCurrentSession().delete(file);
	}

	@Transactional
	@Override
	public void updateFile(Files file) {
		// TODO Auto-generated method stub
		this.sessionFactory.getCurrentSession().update(file);
	}

	@Transactional
	@Override
	public void saveFiles(Files file) {
		// TODO Auto-generated method stub
		System.out.println(file.getId());
		this.sessionFactory.getCurrentSession().save(file);
		System.out.println(file.getId());
	}
	
}

  具体展示如下,其实spring事务配置还有其他配置方式。如需看可以访问《Spring事务配置的5种方法

三 参考文章:

http://www.cnblogs.com/leiOOlei/p/3725911.html

原文地址:https://www.cnblogs.com/yuanfy008/p/4087316.html