本文主要是介绍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 实现事务管理(全注解版)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!