【spring框架】spring之HibernateTemplate

HibernateTemplate是spring对hibernate使用的一个简单封装:
i.设计模式Template Method模板方法
ii.Callback回调(钩子函数)

一般我们写save方法都是
public void save(User u) {
		Session s=null;
		try {
			s=sessionFactory.getCurrentSession();
			s.beginTransaction();
			s.save(u);
			s.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			s.getTransaction().rollback();
		}finally{
			if(s!=null){
				s.close();
				s=null;
			}
		}
		System.out.println("add success!!");		
	}

HibernateTemplate替我们封装了s.save(u);之前和之后的代码,交给我们一个接口,我们去填中间的事务(save等)就行了。这样写程序就会比较方便。

下面来模拟一下HibernateTemplate的封装原理,让我们更好的去理解HibernateTemplate:
MyHibernateTemplate:
package cn.edu.hpu.HibernateTemplate;

import org.hibernate.Session;

public class MyHibernateTemplate {
	public void executeWithNativeSession(MyHibernateCallback callback){
		Session s=null;
		try {
			s=getSession();
			s.beginTransaction();
			
			callback.doInHibernate(s);//这里的方法用户自己就可以在接口里去写(save什么的)
			
			s.getTransaction().commit();
		} catch (Exception e) {
			e.printStackTrace();
			s.getTransaction().rollback();
		}finally{
			if(s!=null){
				s.close();
				s=null;
			}
		}
	}
	
	public Session getSession(){
		//拿Session,这里就省略不写了
		Session session=null;
		return session;
	}
}

MyHibernateCallback.java:
package cn.edu.hpu.HibernateTemplate;

import org.hibernate.Session;

public interface MyHibernateCallback {
	public void doInHibernate(Session s); 
}

//如何去用MyHibernateTemplate方法
	public static void main(String[] args) {
		new MyHibernateTemplate().executeWithNativeSession(new MyHibernateCallback() {
			public void doInHibernate(Session s) {
				s.save(null);//或其他事务
			}
		});
	}
是不是更加理解HibernateTemplate了?
下面来看看如何使用HibernateTemplate。

实现方式:
1.第一种:(建议)
a)在spring中初始化HibernateTemplate,注入sessionFactory
b)DAO里注入HibernateTemplate
c)save写getHibernateTemplate.save()

测试:
beans.xml:
<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx 
           http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
               
  <context:annotation-config/>
  <context:component-scan base-package="cn.edu.hpu"/>


  <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <value>classpath:com/foo/jdbc.properties</value>
    </property>
  </bean>
   
	<bean id="dataSource" destroy-method="close"
	      class="org.apache.commons.dbcp.BasicDataSource">
	    <property name="driverClassName" value="${jdbc.driverClassName}"/>
	    <property name="url" value="${jdbc.url}"/>
	    <property name="username" value="${jdbc.username}"/>
	    <property name="password" value="${jdbc.password}"/>
	</bean>
  
  <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    	<property name="annotatedClasses">
      		<list>
        	<value>cn.edu.hpu.model.User</value>
        	<value>cn.edu.hpu.model.Log</value>
     		</list>
    	</property>
    	<property name="hibernateProperties">
			<props>
		   		<prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
		   		<prop key="hibernate.show_sql">true</prop>
			</props>
    	</property>
  	</bean>
  	<!-- 有关事务的配置 -->
  	<bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
   		 <property name="sessionFactory" ref="sessionFactory"/>
	</bean>
	<!-- tx的Annotation配置 -->
	<!-- <tx:annotation-driven transaction-manager="txManager"/> -->
  	<aop:config>
  		<aop:pointcut expression="execution(public * cn.edu.hpu.service..*.*(..))" id="businessService"/>
  		<aop:advisor pointcut-ref="businessService" advice-ref="txAdvice"/>
  	</aop:config>
  	<tx:advice id="txAdvice" transaction-manager="txManager">
  		<tx:attributes>
    		 <tx:method name="get*" read-only="true"/>
   		     <tx:method name="add*" propagation="REQUIRED"/>
  	    </tx:attributes>
    </tx:advice>


    <!--hibernateTemplate的配置-->
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
	<property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
</beans>

User.java:
package cn.edu.hpu.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class User {
	private int id;
	private String name;


	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}


UserDao.java:
package cn.edu.hpu.dao;

import org.springframework.stereotype.Component;

import cn.edu.hpu.model.User;

public interface UserDao {

	public void save(User u);
}

UserDaoImpl.java:
package cn.edu.hpu.dao.Impl;

import javax.annotation.Resource;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;

import cn.edu.hpu.dao.UserDao;
import cn.edu.hpu.model.User;

@Component("u")
public class UserDaoImpl implements UserDao{
	
	private HibernateTemplate hibernateTemplate;
	
	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	@Resource(name="hibernateTemplate")
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public void save(User u) {
		hibernateTemplate.save(u);
		System.out.println("add success!!");		
	}
	
}

UserService.java:
package cn.edu.hpu.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import cn.edu.hpu.dao.LogDao;
import cn.edu.hpu.dao.UserDao;
import cn.edu.hpu.model.Log;
import cn.edu.hpu.model.User;

@Component("userService")
public class UserService {


	private UserDao userDao;
	
	public UserDao getUserDao() {
		return userDao;
	}
	
	@Resource(name="u")
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
	public void add(User u){
		this.userDao.save(u);
	}
}

测试方法:
UserServiceTest.java:
package cn.edu.hpu.service;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import cn.edu.hpu.model.User;


public class UserServiceTest {
	
	@Test
	public void testAdd() throws Exception{
		ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
		
		UserService userService=(UserService)ctx.getBean("userService");
		System.out.println(userService.getClass());
		User u=new User();
		u.setName("jack");
		userService.add(u);
		ctx.destroy();
	}
}

测试结果:
class cn.edu.hpu.service.UserService$$EnhancerByCGLIB$$30e9ad8d
Hibernate: insert into User (name) values (?)
add success!!
测试成功!!


2.第二种:
a)从HibernateDaoSupport继承
b)必须写在xml文件中,无法使用Annotation,因为set方法在父类中,而且是final的
例子实现:
对一个Log实体类进行save:
不用SessionFactory,也不用get和set这个HIbernateTemplate,只需要从HibernateDaoSupport继承:
package cn.edu.hpu.dao.Impl;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Component;

import cn.edu.hpu.dao.LogDao;
import cn.edu.hpu.model.Log;


@Component("logDao")
public class LogDaoImpl extends HibernateDaoSupport implements LogDao{


	public void save(Log log) {
		this.getHibernateTemplate().save(log);
		//或直接this.save(log);
		System.out.println("Log add success!!");		
	}
}



这里你要在beans.xml中去注入HibernateDaoSupport的SessionFactory:
<?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:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/aop
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
           http://www.springframework.org/schema/tx 
           http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
               
  <context:annotation-config/>
  <context:component-scan base-package="cn.edu.hpu"/>
  
  <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <value>classpath:com/foo/jdbc.properties</value>
    </property>
  </bean>
   
	<bean id="dataSource" destroy-method="close"
	      class="org.apache.commons.dbcp.BasicDataSource">
	    <property name="driverClassName" value="${jdbc.driverClassName}"/>
	    <property name="url" value="${jdbc.url}"/>
	    <property name="username" value="${jdbc.username}"/>
	    <property name="password" value="${jdbc.password}"/>
	</bean>
  
  <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    	<property name="annotatedClasses">
      		<list>
        	<value>cn.edu.hpu.model.User</value>
        	<value>cn.edu.hpu.model.Log</value>
     		</list>
    	</property>
    	<property name="hibernateProperties">
			<props>
		   		<prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQLDialect
                </prop>
		   		<prop key="hibernate.show_sql">true</prop>
			</props>
    	</property>
  
	<bean id="logDao" class="cn.edu.hpu.dao.Impl.LogDaoImpl">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>
</beans>

测试:
package cn.edu.hpu.service;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;


import cn.edu.hpu.model.Log;


public class UserServiceTest {
	
	@Test
	public void testAdd() throws Exception{
		ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
		
		UserService userService=(UserService)ctx.getBean("userService");
		System.out.println(userService.getClass());
		Log log=new Log();
		userService.add(log);
		ctx.destroy();
	}
}
测试结果:
class cn.edu.hpu.service.UserService$$EnhancerByCGLIB$$31bbf2e4
Hibernate: insert into t_log (msg) values (?)
Log add success!!


个人感觉每次使用this.getHibernateTemplate()的时候还要在配置文件里一一配置,不如方法一来得痛快。
也可以用简单的办法去解决这样的问题来更好的使用方法二操纵HibernateTemplate:
单独建立一个类(假设叫Abstrect类)去get和set这个HibernateTemplate,在beans.xml配置文件中注入HibernateTemplate,所有的需要使用HibernateTemplate的类都去继承这个Abstrect类,这时候就可以使用this.getHibernateTemplate()了。就没有必要一一的在beans中配一遍了。
(这里实体类使用的是Annotation,如果全部使用的是XML,就让Abstrect类去继承HibernateDaoSupport)


能不用继承就不用继承,HibernateDaoSupport的使用不太重要,尽量使用方法一吧。

转载请注明出处:http://blog.csdn.net/acmman/article/details/44652207

你可能感兴趣的:(spring,AOP,javaee)