`
tuoni
  • 浏览: 28277 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Spring HibernateTransactionManager事务管理

阅读更多
package com.spring.hibernateTransactionManager;

import org.hibernate.Session;



public interface BaseDao<T> {

	public Session getHibernateSession();

	public void save(Object entity);

	
	

}

 

package com.spring.hibernateTransactionManager;

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

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;


@SuppressWarnings("unchecked")
public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T> {

	public BaseDaoImpl() {
		GenricsUtils.getSuperClassGenricType(getClass());
	}

	public Session getHibernateSession() {
		return this.getSession();
	}

	public void save(Object entity) {
		this.getHibernateTemplate().save(entity);
	}


	public void update(Object entity) {
		this.getHibernateTemplate().update(entity);
	}

	public void saveOrUpdate(Object entity) {
		this.getHibernateTemplate().merge(entity);	
	}

	public void update(String hql) {
		this.getHibernateTemplate().bulkUpdate(hql);

	}

	public void delete(String hql) {
		this.getHibernateTemplate().bulkUpdate(hql);

	}


	public void delete(Object entity) {
		this.getHibernateTemplate().delete(entity);
	}


	public List<T> find(String hql, Object... values) {
		return this.getHibernateTemplate().find(hql, values);
	}
	
	public T first(String hql, Object... values) {
		Iterator i = this.getHibernateTemplate().iterate(hql, values);
		if (i.hasNext()) {
			return (T) i.next();
		} else {
			return null;
		}
	}	
	public boolean isExists(String hql, Object... values) {
		return !this.getHibernateTemplate().find(hql, values).isEmpty();
	}		
	@SuppressWarnings("hiding")
	public <T> T get(Class<T> entityClass,Serializable id) {
		return (T) getHibernateTemplate().get(entityClass, id);
	
	}
	
	public List<T> find(String hql, int startIndex, int pageSize,
			Object... values) {
		Query query = getSession().createQuery(hql);
		query.setFirstResult(startIndex);
		query.setMaxResults(pageSize);
		for (int i = 0; i < values.length; i++) {
			query.setParameter(i, values[i]);
		}
		return query.list();
	}
}

 

package com.spring.hibernateTransactionManager;

import java.lang.reflect.ParameterizedType;

import java.lang.reflect.Type;

public class GenricsUtils {

	
	private GenricsUtils(){}
	
	@SuppressWarnings("rawtypes")
	public static Class getSuperClassGenricType(Class clazz){
		return getSuperClassGenricType(clazz, 0);
	}
	
	/**
	 * 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends GenricManager<Book>
	 *
	 * @param clazz clazz The class to introspect
	 * @param index the Index of the generic ddeclaration,start from 0.
	 * @return the index generic declaration, or <code>Object.class</code> if cannot be determined
	 */
	@SuppressWarnings("rawtypes")
	public static Class getSuperClassGenricType(Class clazz, int index) {

		Type genType = clazz.getGenericSuperclass();
		if (!(genType instanceof ParameterizedType)) {
			return Object.class;
		}

		Type[] params = ((ParameterizedType) genType).getActualTypeArguments();

		if (index >= params.length || index < 0) {
			return Object.class;
		}
		if (!(params[index] instanceof Class)) {
			return Object.class;
		}
		return (Class) params[index];
	}	
}

 

package com.spring.hibernateTransactionManager;

import com.spring.model.Product;
import com.spring.model.Receiver;

public interface ProductManager {
	
	public void save(Product p);
	
	public void save(Product p, Receiver r);

}

 

package com.spring.hibernateTransactionManager;


import com.spring.model.Product;
import com.spring.model.Receiver;

public class ProductManagerImpl implements ProductManager{
	
	private BaseDao<Product> baseDao;
	
	private BaseDao<Receiver> baseRDao;
	
	@Override
	public void save(Product p) {
		baseDao.save(p);
	}
	
	
	public void save(Product p, Receiver r) {
		baseDao.save(p);
		baseRDao.save(r);
	}

	public BaseDao<Product> getBaseDao() {
		return baseDao;
	}

	public void setBaseDao(BaseDao<Product> baseDao) {
		this.baseDao = baseDao;
	}

	public BaseDao<Receiver> getBaseRDao() {
		return baseRDao;
	}

	public void setBaseRDao(BaseDao<Receiver> baseRDao) {
		this.baseRDao = baseRDao;
	}
	
}

 

database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://127.0.0.1/jinhonglun?useEncoding=true&characterEncoding=UTF-8
database.username=root
database.password=root
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true


 

<?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="
	http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.5.xsd
	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
	
    <!-- 获取资源文件 -->
	<bean id="configurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations" value="classpath:/com/spring/dataSourceTransactionManager/configuration.properties" />
		
		<!-- 获取多个资源文件 
		 <property name="locations">
		     <list>
		        <value>classpath:/com/zsw/config/jdbc.properties</value>
		     </list>
  		</property>
  		-->
  		<!--  使用location属性定义单个配置文件
        <property name="location">
            <value>classpath:/com/zsw/config/jdbc.properties</value>
        </property>
         -->
  
	</bean>
	
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
	    destroy-method="close">
	    <property name="driverClassName" value="${database.driver}" />
	    <property name="url" value="${database.url}" />
	    <property name="username" value="${database.username}" />
	    <property name="password" value="${database.password}" />
	    <property name="timeBetweenEvictionRunsMillis" value="300000" />
	    <property name="numTestsPerEvictionRun" value="6" />
	    <property name="minEvictableIdleTimeMillis" value="1800000" />
	    <property name="initialSize" value="3" />
	    <property name="maxActive" value="10" />
	    <property name="maxIdle" value="10" />
	    <property name="maxWait" value="5000" />
	    <property name="poolPreparedStatements" value="true" />
	    <property name="maxOpenPreparedStatements" value="100" />
	</bean>
	
	<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">  
        <property name="dataSource" ref="dataSource"/>  
		<property name="mappingLocations">
		    <value>classpath:/com/spring/model/*.hbm.xml</value>
		</property>
        <property name="hibernateProperties">  
            <props>  
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.show_sql">false</prop>   
                <prop key="hibernate.hbm2ddl.auto">update</prop>  
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>  
				<prop key="hibernate.query.substitutions" >true 1, false 0</prop>                
            </props>  
        </property>  
    </bean> 
    
    <bean id="baseDao" class="com.spring.hibernateTransactionManager.BaseDaoImpl" >
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
	
	 <bean id="productManager" class="com.spring.hibernateTransactionManager.ProductManagerImpl" >
		<property name="baseDao" ref="baseDao"></property>
		<property name="baseRDao" ref="baseDao"></property>
	</bean>
	<!-- 
		位于org.springframework.orm.hibernate3包中,提供对单个org.hibernate.SessionFactory事务支持,
		用于集成Hibernate框架时的事务管理;该事务管理器只支持Hibernate3+版本,且Spring3.0+版本只支持Hibernate 3.2+版本;
	 -->	
	 <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">  
        <property name="sessionFactory" ref="sessionFactory"></property>  
     </bean>
	
    <!-- 采用AOP机制切面管理事务 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="get*" read-only="true" />
			<tx:method name="processNotifyTrade" propagation="REQUIRES_NEW" />				
			<tx:method name="*" propagation="REQUIRED" />
		</tx:attributes>
	</tx:advice>
	<!-- 
		解释一下(* com.evan.crm.service.*.*(..))中几个通配符的含义: 第一个 * —— 通配 任意返回值类型 
		第二个 * —— 通配 包com.evan.crm.service下的任意class 
		第三个 * —— 通配 包com.evan.crm.service下的任意class的任意方法 第四个 .. —— 通配 方法可以有0个或多个参数
	 -->
 	<aop:config>  
        <aop:pointcut expression="execution(public * com.spring.hibernateTransactionManager..*.*(..))" id="servicePointcut"/>  
        <aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointcut"/>  
     </aop:config>  
</beans>

 

package com.spring.hibernateTransactionManager;

import java.sql.SQLException;
import javax.naming.NamingException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

import com.spring.model.Product;
import com.spring.model.Receiver;

public class TestHibernate {

	public static void main(String[] args) throws NamingException, SQLException {
		ApplicationContext app = new FileSystemXmlApplicationContext("src/com/spring/hibernateTransactionManager/spring-hibernate.xml");
		
		ProductManager productManager = (ProductManager)app.getBean("productManager");
		
		Product p = new Product();
		p.setProductTitle("阿萨啊啊阿");
		
		Receiver r = new Receiver();
		
		productManager.save(p, r);
		
		
	}
	
}

 

分享到:
评论

相关推荐

    spring五种事务配置demo

    测试spring事务管理 搭建了ssh框架的web工程 本工程用到的数据库表很简单 user(id, name) 可自行创建 本例所有的事务放在service层进行管理,方法中间抛出运行时异常以测试是否回滚 Spring配置文件中关于事务...

    Spring事务配置的五种方式

    Spring配置文件中关于事务配置总是由三个组成部分,分别是DataSource、TransactionManager和代理机制这三部分,无论哪种配置方式,一般变化的只是代理机制这部分。 DataSource、TransactionManager这两部分只是会...

    Spring + Hibernate + Struts 事务配置小例子(带提示框等小技巧)

    class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt; &lt;!-- 配置事务拦截器--&gt; class="org.springframework.transaction.interceptor.TransactionInterceptor"&gt; &lt;!-- 事务拦截...

    Spring事务配置的五种方法

    Spring事务配置的五种方法 Spring配置文件中关于事务配置总是由三个组成部分,分别是DataSource、TransactionManager和代理机制这三部分,无论哪种配置方式,一般变化的只是代理机制这部分。 DataSource、...

    Spring事务配置5种方式

    Spring事务配置5种方式 Spring配置文件中关于事务配置总是由三个组成部分,分别是DataSource、TransactionManager和代理机制这三部分,无论哪种配置方式,一般变化的只是代理机制这部分。 DataSource、...

    spring分别与jdbc和hibernate结合的事务控制--案例

    本案例主要是分别实现Spring与jdbc和hibernate结合的事务控制,如果该案例有出入的地方,请给我留言,我们一起交流

    spring3.2+strut2+hibernate4

    &lt;bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"&gt; &lt;property name="sessionFactory" ref="sessionFactory" /&gt; &lt;/bean&gt; &lt;!-- JTA环境的事务配置 ...

    ssh(structs,spring,hibernate)框架中的上传下载

    Struts+Spring+Hibernate实现上传下载    本文将围绕SSH文件上传下载的主题,向您详细讲述如何开发基于SSH的Web程序。SSH各框架的均为当前最新版本:  •Struts 1.2  •Spring 1.2.5  •Hibernate 3.0  本文...

    SSH整合&&SSH集成开发

    &lt;bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt; &lt;!-- JTA环境的事务配置 &lt;bean id="transactionManager" class="org.springframework....

    SSH第7章上机.zip ACCP8.0

    -- 创建事务管理器(spring针对hibernate实现的事务管理的切面类) --&gt; &lt;bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"&gt; &lt;!-- 事务的通知类型 -...

    客户关系管理系统框架搭建(二)

    --4 创建事务管理器 aop切面--&gt; &lt;bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt; &lt;!--5 配置处理事务的注解--&gt; * 创建dao...

    ssh框架在application.xml中配置数据源所需jar

    -- 配置事务管理器 --&gt; &lt;bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt; &lt;/property&gt; &lt;!-- 配置事务的传播特性 --&gt; *" ...

    维生药业小项目 SSH简单学习项目

    class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt; &lt;!-- 使用annotation定义事务 --&gt; proxy-target-class="true" /&gt; &lt;!-- 使用annotation 自动注册bean,并检查@Required,@...

    Myeclipse6.0中SSH框架搭建

    class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt; &lt;property name="sessionFactory" ref="sessionFactory"&gt;&lt;/property&gt; &lt;/bean&gt; &lt;!-- 其它Bean定义在此 --&gt; &lt;!-- 定义拦截器 --&gt; ...

    SpringMVC+Hibernate全注解整合

    class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt; &lt;!-- Spring AOP config配置切点 --&gt; (public * com.org.service.*.*(..))" id="bussinessService" /&gt; &lt;!-- 配置...

    OA项目SSH整合框架

    -- 配置事务管理器 --&gt; &lt;bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt; &lt;property name="sessionFactory" ref="sessionFactory"&gt;&lt;/property&gt; ...

    SpringMVC-SSH全注解

    class="org.springframework.orm.hibernate3.HibernateTransactionManager"&gt; &lt;!-- Spring AOP config配置切点 --&gt; (public * com.org.core.service.*.*(..))" id="bussinessService" /&gt; &lt;!--...

Global site tag (gtag.js) - Google Analytics