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

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听