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

2024-09-07 14:18

本文主要是介绍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;//注意是AnnotationSessionFactoryBeanpublic AnnotationSessionFactoryBean getSessionFactory() {return sessionFactory;}@Autowiredpublic 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;}@Autowiredpublic 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.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://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="org.springframework.web.servlet.view.JstlView"/>  <property name="prefix" value="/pages/"/>  <property name="suffix" value=".jsp"/> </bean> <!--静态文件的访问--><mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/><mvc:resources mapping="/common/**" location="/common/" cache-period="31556926"/> <mvc:resources mapping="/jslib/**" location="/jslib/" cache-period="31556926"/> <mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/> <mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/>  <!-- 支持json返回 --><bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">      <property name="messageConverters">      <list >      <ref bean="mappingJacksonHttpMessageConverter" />      </list>      </property>      </bean>  <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">    <property name="supportedMediaTypes">    <list>    <value>application/json;charset=UTF-8</value>    </list>    </property>  </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="com.mysql.jdbc.Driver"> </property> <property name="url" value="jdbc:mysql://localhost:3306/test"></property> <property name="username" value="root"/><property name="password" value=""/></bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"><!--注解专用session --><property name="dataSource"><ref bean="dataSource" /></property><property name="hibernateProperties"><props><prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect </prop><prop key="hibernate.show_sql">true</prop> </props></property><property name="annotatedClasses"><!--看,mappingresource消失了 --><list><value>Sand.mas.model.User</value></list></property></bean><!-- 配置事务管理器bean,使用HibernateTransactionManager事务管理器 --><bean id="transactionManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager"><!-- 为事务管理器注入sessionFactory" --><property name="sessionFactory" ref="sessionFactory"/></bean><!-- 注解实现事务 --><tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />
</beans>

原文地址:http://www.itnose.net/detail/6102205.html

这篇关于spring mvc+hibernate 实现事务管理(全注解版)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1145296

相关文章

windos server2022里的DFS配置的实现

《windosserver2022里的DFS配置的实现》DFS是WindowsServer操作系统提供的一种功能,用于在多台服务器上集中管理共享文件夹和文件的分布式存储解决方案,本文就来介绍一下wi... 目录什么是DFS?优势:应用场景:DFS配置步骤什么是DFS?DFS指的是分布式文件系统(Distr

NFS实现多服务器文件的共享的方法步骤

《NFS实现多服务器文件的共享的方法步骤》NFS允许网络中的计算机之间共享资源,客户端可以透明地读写远端NFS服务器上的文件,本文就来介绍一下NFS实现多服务器文件的共享的方法步骤,感兴趣的可以了解一... 目录一、简介二、部署1、准备1、服务端和客户端:安装nfs-utils2、服务端:创建共享目录3、服

SpringBoot使用Apache Tika检测敏感信息

《SpringBoot使用ApacheTika检测敏感信息》ApacheTika是一个功能强大的内容分析工具,它能够从多种文件格式中提取文本、元数据以及其他结构化信息,下面我们来看看如何使用Ap... 目录Tika 主要特性1. 多格式支持2. 自动文件类型检测3. 文本和元数据提取4. 支持 OCR(光学

Java内存泄漏问题的排查、优化与最佳实践

《Java内存泄漏问题的排查、优化与最佳实践》在Java开发中,内存泄漏是一个常见且令人头疼的问题,内存泄漏指的是程序在运行过程中,已经不再使用的对象没有被及时释放,从而导致内存占用不断增加,最终... 目录引言1. 什么是内存泄漏?常见的内存泄漏情况2. 如何排查 Java 中的内存泄漏?2.1 使用 J

JAVA系统中Spring Boot应用程序的配置文件application.yml使用详解

《JAVA系统中SpringBoot应用程序的配置文件application.yml使用详解》:本文主要介绍JAVA系统中SpringBoot应用程序的配置文件application.yml的... 目录文件路径文件内容解释1. Server 配置2. Spring 配置3. Logging 配置4. Ma

Java 字符数组转字符串的常用方法

《Java字符数组转字符串的常用方法》文章总结了在Java中将字符数组转换为字符串的几种常用方法,包括使用String构造函数、String.valueOf()方法、StringBuilder以及A... 目录1. 使用String构造函数1.1 基本转换方法1.2 注意事项2. 使用String.valu

C#使用yield关键字实现提升迭代性能与效率

《C#使用yield关键字实现提升迭代性能与效率》yield关键字在C#中简化了数据迭代的方式,实现了按需生成数据,自动维护迭代状态,本文主要来聊聊如何使用yield关键字实现提升迭代性能与效率,感兴... 目录前言传统迭代和yield迭代方式对比yield延迟加载按需获取数据yield break显式示迭

Python实现高效地读写大型文件

《Python实现高效地读写大型文件》Python如何读写的是大型文件,有没有什么方法来提高效率呢,这篇文章就来和大家聊聊如何在Python中高效地读写大型文件,需要的可以了解下... 目录一、逐行读取大型文件二、分块读取大型文件三、使用 mmap 模块进行内存映射文件操作(适用于大文件)四、使用 pand

python实现pdf转word和excel的示例代码

《python实现pdf转word和excel的示例代码》本文主要介绍了python实现pdf转word和excel的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价... 目录一、引言二、python编程1,PDF转Word2,PDF转Excel三、前端页面效果展示总结一

java脚本使用不同版本jdk的说明介绍

《java脚本使用不同版本jdk的说明介绍》本文介绍了在Java中执行JavaScript脚本的几种方式,包括使用ScriptEngine、Nashorn和GraalVM,ScriptEngine适用... 目录Java脚本使用不同版本jdk的说明1.使用ScriptEngine执行javascript2.