HiberateTemplate

 设计模式: Template Method

1.在Spring中初始化HiberateTemplate ,注入 sessionFactory

2.Dao里注入HiberateTemplate

3.save 写getHiberateTemplate.save();


配置hiberateTemplate 的bean.xml 片段如下:

	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory" ref="sessionFactory"></property>
	</bean>

<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<!-- 
		<property name="annotatedClasses">
			<list>
				<value>com.bjsxt.model.User</value>
				<value>com.bjsxt.model.Log</value>
			</list>
		</property>
		 -->
		 <property name="packagesToScan">
			<list>
				<value>com.bjsxt.model</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>

然后在userDaoImpl类里面注入。

@Component("u") 
public class UserDAOImpl implements UserDAO {

	private HibernateTemplate hibernateTemplate;

	

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}


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



	public void save(User user) {
		
			hibernateTemplate.save(user);
			
		//throw new RuntimeException("exeption!");
	}

}

实现原理就是在hiberateTemplate把公共代码写好:比如开头于结尾,中间的通过一个接口回调暴露给程序员
public class MyHibernateTemplate {
	public void executeWithNativeSession(MyHibernateCallback callback) {
		Session s = null;
		try {
			s = getSession();
			s.beginTransaction();
			
			callback.doInHibernate(s);//注意这个session在后来实现的时候可以直接用,暴露出去
			
			s.getTransaction().commit();
		} catch (Exception e) {
			s.getTransaction().rollback();
		} finally {
			//...
		}
	}

	private Session getSession() {
		// TODO Auto-generated method stub
		return null;
	}
	
	public void save(final Object o) {
		
		new MyHibernateTemplate().executeWithNativeSession(new MyHibernateCallback() {
			public void doInHibernate(Session s) {
				s.save(o);//直接用s
				
			}
		});
	}

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


你可能感兴趣的:(template,Hiberate)