首页 > 代码库 > spring mvc+hibernate 实现事务管理(全注解版)

spring mvc+hibernate 实现事务管理(全注解版)

为了方便项目变大配置文件变多,用注解代替 *.hbm.xml,<bean id="*dao" class="">,另外用反省实现dao操作,省去每个类一个dao,此处参考了鸵鸟的例子。

实现功能跟http://blog.csdn.net/waiwai4701/article/details/38270721这个项目是一样的,controller和页面就不再写

首先,jar包支持,为了方便jar包管理采用maven技术,服务器没有用tomcat用的jetty,不要在意这些细节

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>Sand</groupId>
  <artifactId>mas</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>mas</name>
  <url>http://maven.apache.org</url>


  
   <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>3.2.5.RELEASE</spring.version>
	<curator_version>1.1.16</curator_version>
	<slf4j_version>1.6.2</slf4j_version>
	<jcl_version>1.1</jcl_version>
	<log4j_version>1.2.16</log4j_version>
	<jetty.version>8.1.8.v20121106</jetty.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
   	<dependency>
      <groupId>org.jdom</groupId>
      <artifactId>jdom</artifactId>
      <version>1.1.3</version>
    </dependency>
    
    	<dependency>
    		<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j_version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${slf4j_version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j_version}</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j_version}</version>
		</dependency>
		<!-- springframework -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>3.2.5.RELEASE</version>
			<exclusions>
				<exclusion>
					<groupId>commons-logging</groupId>
					<artifactId>commons-logging</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
    
    <!-- for jetty -->
    <dependency>
	  <groupId>org.eclipse.jetty</groupId>
	  <artifactId>jetty-server</artifactId>
	  <version>${jetty.version}</version>
	</dependency>
	
	<dependency>
	  <groupId>org.eclipse.jetty</groupId>
	  <artifactId>jetty-util</artifactId>
	  <version>${jetty.version}</version>
	</dependency>
    
    <dependency>
	  <groupId>org.eclipse.jetty</groupId>
	  <artifactId>jetty-xml</artifactId>
	  <version>${jetty.version}</version>
	</dependency>
	
	<dependency>
	  <groupId>org.eclipse.jetty</groupId>
	  <artifactId>jetty-webapp</artifactId>
	  <version>${jetty.version}</version>
	</dependency>
	<dependency>  
	    <groupId>org.eclipse.jetty</groupId>  
	    <artifactId>jetty-jsp</artifactId>  
	    <version>${jetty.version}</version>  
	</dependency>  
	 <!-- spring mvc -->
    <dependency>  
      <groupId>org.springframework</groupId>  
      <artifactId>spring-web</artifactId>  
      <version>3.2.5.RELEASE</version>  
    </dependency>  
    
    <dependency>  
       <groupId>org.springframework</groupId>  
       <artifactId>spring-webmvc</artifactId>  
       <version>3.2.5.RELEASE</version>  
    </dependency> 
    <dependency>  
       <groupId>org.springframework</groupId>  
       <artifactId>spring-orm</artifactId>  
       <version>3.2.5.RELEASE</version>  
    </dependency> 
	<dependency>
		<groupId>javax.servlet.jsp.jstl</groupId>
		<artifactId>jstl-api</artifactId>
		<version>1.2-rev-1</version>
	</dependency>
    
     <dependency>  
        <groupId>javax.servlet</groupId>  
        <artifactId>jstl</artifactId>  
        <version>1.2</version>  
        <scope>runtime</scope>  
     </dependency>  
     <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
     </dependency>
    
    <dependency>  
		<groupId>org.codehaus.jackson</groupId>  
    	<artifactId>jackson-core-lgpl</artifactId>  
    	<version>1.9.6</version>  
	</dependency>  
	<dependency>  
		<groupId>org.codehaus.jackson</groupId>  
    	<artifactId>jackson-core-asl</artifactId>  
    	<version>1.9.4</version>  
	</dependency>  
	<dependency>  
		<groupId>org.codehaus.jackson</groupId>  
    	<artifactId>jackson-mapper-asl</artifactId>  
    	<version>1.9.5</version>  
	</dependency>  
	<dependency>  
  	  <groupId>org.codehaus.jackson</groupId>  
   	  <artifactId>jackson-mapper-lgpl</artifactId>  
  	  <version>1.9.6</version>  
	</dependency>  
	<!-- memcached -->
    <dependency>
		<groupId>com.danga</groupId>
  		<artifactId>java-memcached</artifactId>
  		<version>2.6.6</version>
	</dependency>
	<!-- hibernate -->
	<dependency>
		<groupId>org.hibernate</groupId>
  		<artifactId>hibernate</artifactId>
  		<version>3.3.2</version>
	</dependency>
	<!-- mysql -->
	 <dependency>
		<groupId>mysql</groupId>
  		<artifactId>mysql-connector-java</artifactId>
  		<version>5.1.21</version>
	</dependency>
	<!-- oracle -->
	<dependency>
		<groupId>oracle</groupId>
  		<artifactId>ojdbc</artifactId>
  		<version>14</version>
	</dependency> 	
	<!-- datasource -->
	<dependency>
		<groupId>commons-dbcp</groupId>
  		<artifactId>commons-dbcp</artifactId>
  		<version>1.4</version>
	</dependency>
	<!-- jta -->
	<dependency>
		<groupId>javax.transaction</groupId>
  		<artifactId>jta</artifactId>
  		<version>1.1</version>
	</dependency>
	<!-- dom4j -->
	<dependency>
	   <groupId>dom4j</groupId>
  		<artifactId>dom4j</artifactId>
	   <version>1.6.1</version>
	</dependency>
	<!-- commons-collections -->
	<dependency>
	    <groupId>commons-collections</groupId>
	    <artifactId>commons-collections</artifactId>
	    <version>3.1</version>
	</dependency>
	<!-- javaassist -->
	 <dependency>
      <groupId>javassist</groupId>
      <artifactId>javassist</artifactId>
      <version>3.9.0</version>
    </dependency>
    <!-- hibernate-annotation -->
 
     <dependency>
      <groupId>javax.persistence</groupId>
      <artifactId>persistence-api</artifactId>
      <version>1.0</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-annotations</artifactId>
      <version>3.4.0.GA</version>
    </dependency>
    <dependency>
       <groupId>org.hibernate</groupId>
       <artifactId>hibernate-commons-annotations</artifactId>
       <version>3.3.0.ga</version>
    </dependency>
     <dependency>
       <groupId>org.hibernate</groupId>
       <artifactId>ejb3-persistence</artifactId>
       <version>1.0.2.GA</version>
    </dependency>
  </dependencies>
</project>
实体类:

package Sand.mas.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "tuser")
public class User implements Serializable {
	private static final long serialVersionUID = 1L;

	private String id;
	
	private String userName;
	
	private String password;
	
	public User(){
		
	}
	
	public User(String userName,String password){
		this.userName = userName;
		this.password = password;
	}

	@Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, nullable = false)
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	 @Column(name = "username", length = 20)
	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}
	
	@Column(name = "password", length = 20)
	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String toString(){
		
		return "user:id="+id+",userName="+userName+",password="+password;
	}
	
}

一些基础用于扩展的东西:

BaseDao

package Sand.mas.sys;

import java.io.Serializable;
import java.util.List;

public interface BaseDao<T> {


	/**
	 * 保存一个对象
	 * 
	 * @param o
	 * @return
	 */
	public Serializable save(T o);

	/**
	 * 删除一个对象
	 * 
	 * @param o
	 */
	public void delete(T o);

	/**
	 * 更新一个对象
	 * 
	 * @param o
	 */
	public void update(T o);

	/**
	 * 保存或更新对象
	 * 
	 * @param o
	 */
	public void saveOrUpdate(T o);

	/**
	 * 查询
	 * 
	 * @param hql
	 * @return
	 */
	public List<T> find(String hql);

	/**
	 * 查询集合
	 * 
	 * @param hql
	 * @param param
	 * @return
	 */
	public List<T> find(String hql, Object[] param);

	/**
	 * 查询集合
	 * 
	 * @param hql
	 * @param param
	 * @return
	 */
	public List<T> find(String hql, List<Object> param);

	/**
	 * 查询集合(带分页)
	 * 
	 * @param hql
	 * @param param
	 * @param page
	 *            查询第几页
	 * @param rows
	 *            每页显示几条记录
	 * @return
	 */
	public List<T> find(String hql, Object[] param, Integer page, Integer rows);

	/**
	 * 查询集合(带分页)
	 * 
	 * @param hql
	 * @param param
	 * @param page
	 * @param rows
	 * @return
	 */
	public List<T> find(String hql, List<Object> param, Integer page, Integer rows);

	/**
	 * 获得一个对象
	 * 
	 * @param c
	 *            对象类型
	 * @param id
	 * @return Object
	 */
	public T get(Class<T> c, Serializable id);

	/**
	 * 获得一个对象
	 * 
	 * @param hql
	 * @param param
	 * @return Object
	 */
	public T get(String hql, Object[] param);

	/**
	 * 获得一个对象
	 * 
	 * @param hql
	 * @param param
	 * @return
	 */
	public T get(String hql, List<Object> param);

	/**
	 * select count(*) from 类
	 * 
	 * @param hql
	 * @return
	 */
	public Long count(String hql);

	/**
	 * select count(*) from 类
	 * 
	 * @param hql
	 * @param param
	 * @return
	 */
	public Long count(String hql, Object[] param);

	/**
	 * select count(*) from 类
	 * 
	 * @param hql
	 * @param param
	 * @return
	 */
	public Long count(String hql, List<Object> param);

	/**
	 * 执行HQL语句
	 * 
	 * @param hql
	 * @return 响应数目
	 */
	public Integer executeHql(String hql);

	/**
	 * 执行HQL语句
	 * 
	 * @param hql
	 * @param param
	 * @return 响应数目
	 */
	public Integer executeHql(String hql, Object[] param);

	/**
	 * 执行HQL语句
	 * 
	 * @param hql
	 * @param param
	 * @return
	 */
	public Integer executeHql(String hql, List<Object> param);


}

BaseDao实现类BaseDaoImpl

package Sand.mas.sys;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;
import org.springframework.stereotype.Repository;

@Repository("baseDao")
public class BaseDaoImpl<T> implements BaseDao<T> {
	
	
	private AnnotationSessionFactoryBean sessionFactory;//注意是AnnotationSessionFactoryBean
	
	public AnnotationSessionFactoryBean getSessionFactory() {
		return sessionFactory;
	}

	@Autowired
	public void setSessionFactory(AnnotationSessionFactoryBean sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	private Session getCurrentSession(){
		return sessionFactory.getObject().getCurrentSession();//还是可以得到session
	}

	public Serializable save(T o) {
		return this.getCurrentSession().save(o);
	}

	public void delete(T o) {
		this.getCurrentSession().delete(o);
		
	}

	public void update(T o) {
		this.getCurrentSession().update(o);
		
	}

	public void saveOrUpdate(T o) {
		this.getCurrentSession().saveOrUpdate(o);
		
	}

	@SuppressWarnings("unchecked")
	public List<T> find(String hql) {
		
		return this.getCurrentSession().createQuery(hql).list();
	}

	@SuppressWarnings("unchecked")
	public List<T> find(String hql, Object[] param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if(param != null && param.length > 0){
			for(int i = 0;i<param.length;i++){
				q.setParameter(i, param[i]);
			}
		}
		return q.list();
	}

	@SuppressWarnings("unchecked")
	public List<T> find(String hql, List<Object> param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if(param != null && param.size() > 0){
			for(int i = 0;i<param.size();i++){
				q.setParameter(i, param.get(i));
			}
		}
		return q.list();
	}

	@SuppressWarnings("unchecked")
	public List<T> find(String hql, Object[] param, Integer page, Integer rows) {
		if(page == null || page < 1){
			page = 1;
		}
		if(rows == null || rows < 1){
			rows = 10;
		}
		
		Query q = this.getCurrentSession().createQuery(hql);
		
		if(param != null && param.length > 0 ){
			for(int i = 0;i< param.length;i++){
				q.setParameter(i, param[i]);
			}
		}
		return q.setFirstResult((page-1)*rows).setMaxResults(rows).list();
	}

	@SuppressWarnings("unchecked")
	public List<T> find(String hql, List<Object> param, Integer page,Integer rows) {
		if (page == null || page < 1) {
			page = 1;
		}
		if (rows == null || rows < 1) {
			rows = 10;
		}
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.size() > 0) {
			for (int i = 0; i < param.size(); i++) {
				q.setParameter(i, param.get(i));
			}
		}
		return q.setFirstResult((page - 1) * rows).setMaxResults(rows).list();
	}

	@SuppressWarnings("unchecked")
	public T get(Class<T> c, Serializable id) {
		return (T)this.getCurrentSession().get(c , id);
	}

	public T get(String hql, Object[] param) {
		List<T> l = this.find(hql, param);
		if(l != null && l.size() > 0){
			return l.get(0);
		}else{
			return null;
		}
	}

	public T get(String hql, List<Object> param) {
		List<T> l = this.find(hql, param);
		if (l != null && l.size() > 0) {
			return l.get(0);
		} else {
			return null;
		}
	}

	public Long count(String hql) {
		return (Long)this.getCurrentSession().createQuery(hql).uniqueResult();
	}

	public Long count(String hql, Object[] param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				q.setParameter(i, param[i]);
			}
		}
		return (Long) q.uniqueResult();
	}

	public Long count(String hql, List<Object> param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.size() > 0) {
			for (int i = 0; i < param.size(); i++) {
				q.setParameter(i, param.get(i));
			}
		}
		return (Long) q.uniqueResult();
	}

	public Integer executeHql(String hql) {
		return this.getCurrentSession().createQuery(hql).executeUpdate();
	}

	public Integer executeHql(String hql, Object[] param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.length > 0) {
			for (int i = 0; i < param.length; i++) {
				q.setParameter(i, param[i]);
			}
		}
		return q.executeUpdate();
	}

	public Integer executeHql(String hql, List<Object> param) {
		Query q = this.getCurrentSession().createQuery(hql);
		if (param != null && param.size() > 0) {
			for (int i = 0; i < param.size(); i++) {
				q.setParameter(i, param.get(i));
			}
		}
		return q.executeUpdate();
	}

}

BaseService:

package Sand.mas.sys;

public interface BaseService {
//也就是直接性的什么都没有,只为了实现类节省每个扩展service的@transaction
}

实现类 BaseServiceImpl:

package Sand.mas.sys;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service("baseService")
@Transactional(readOnly = false,propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
public class BaseServiceImpl implements BaseService{

}


UserService:

package Sand.mas.service;

public interface UserService {

	public void test();
}
UserServiceImpl:

package Sand.mas.service.impl;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import Sand.mas.model.User;
import Sand.mas.service.UserService;
import Sand.mas.sys.BaseDao;
import Sand.mas.sys.BaseServiceImpl;


@Service("userService")
public class UserServiceImpl extends BaseServiceImpl implements UserService{
	
	private BaseDao<User> userDao;//看到妙处没
	
	public BaseDao<User> getUserDao() {
		return userDao;
	}
	@Autowired
	public void setUserDao(BaseDao<User> userDao) {
		this.userDao = userDao;
	}

	@Transactional(rollbackFor=Exception.class)
	public void test() {
		User user1 = new User("zhangsan","111111");
		
		User user2 = new User("lisi","222222222222222222222222222222");
		
		userDao.save(user1);
		System.out.println("user1 success");
		
		userDao.save(user2);
		System.out.println("user2 success");
		
	}

	
}

最后,配置文件,折腾了姐好久

<?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:context="http://www.springframework.org/schema/context"  
        xmlns:mvc="http://www.springframework.org/schema/mvc"  
        xmlns:cache="http://www.springframework.org/schema/cache"
         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.2.xsd  
          http://www.springframework.org/schema/context  
          http://www.springframework.org/schema/context/spring-context-3.2.xsd  
          http://www.springframework.org/schema/mvc      
          http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
          http://www.springframework.org/schema/tx
 		  http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
          http://www.springframework.org/schema/cache 
          http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">
  <!--扫描的包-->
  <context:component-scan base-package="Sand.mas"/>
  <!--注解支持-->
  <mvc:annotation-driven/>
  <!--视图解析-->
  <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> 
    	<property name="viewClass" value=http://www.mamicode.com/"org.springframework.web.servlet.view.JstlView"/>  >源码下载地址:http://download.csdn.net/detail/waiwai4701/7833547




spring mvc+hibernate 实现事务管理(全注解版)