读书人

Spring跟Hibernate整合

发布时间: 2013-08-04 18:26:16 作者: rapoo

Spring和Hibernate整合
?</bean>

3、让Common继承HibernateDaoSupport类,该类提供了HibernateTemplate的getter和setter方法。

4、将hibernateTemplete注入到Common中
?<bean id="common" ref="hibernateTemplete"></property>
?</bean>

5、将Common的方法修改成hibernateTemplete的操作。
package com.aptech.common;

import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.aptech.exception.CommonException;
import com.aptech.htm.HibernateSessionFactory;
/**
?* 通用类,不再负责事务处理
?* 目标对象
?* @author 李赞红
?*
?* @param <POJO>
?*/
public class Common<POJO> extends HibernateDaoSupport implements ICommon<POJO> {
?public void insertObject(POJO pojo) throws CommonException {
??try {
???this.getHibernateTemplate().save(pojo);
??} catch (DataAccessException e) {
???e.printStackTrace();
???throw new CommonException(e);
??}
?}

?public void updateObject(POJO pojo) throws CommonException {
??try {
???this.getHibernateTemplate().update(pojo);
??} catch (DataAccessException e) {
???e.printStackTrace();
???throw new CommonException(e);
??}
?}

?public void deleteObject(Class theClass, long id) throws CommonException {
??try {
???Object obj = this.getHibernateTemplate().load(theClass, id);
???this.getHibernateTemplate().delete(obj);
??} catch (DataAccessException e) {
???// TODO Auto-generated catch block
???e.printStackTrace();
???throw new CommonException(e);
??}
?}

?public POJO loadObject(Class theClass, long id) throws CommonException {
??try {
???Object obj = this.getHibernateTemplate().load(theClass, id);
???return (POJO) obj;
??} catch (DataAccessException e) {
???// TODO Auto-generated catch block
???e.printStackTrace();
???throw new CommonException(e);
??}
?}

?public List queryObjects(final String hql) throws CommonException {
??class Hc implements HibernateCallback{
???public Object doInHibernate(Session session)
?????throws HibernateException, SQLException {
????return session.createQuery(hql).list();
???}
??}
??
??try {
???return this.getHibernateTemplate().executeFind(new Hc());
??} catch (DataAccessException e) {
???e.printStackTrace();
???throw new CommonException(e);
??}
?}

?public List queryObjects(Class theClazz) throws CommonException {
??return this.queryObjects("from " + theClazz.getSimpleName());
?}
}


6、配置事务
<!-- 事务管理器,相当于TransactionProxy,定义事务的开启、提交、回滚 -->
?<bean id="htm" abstract="true">
??<property name="common">
???<ref bean="common"/>
??</property>
?</bean>
?
?<bean id="udao" parent="baseDao"></bean>
?<bean id="rdao" parent="baseDao"></bean>


8、将Dao注入Service
?<bean id="grantService" ref="rdao"></property>
??<property name="udao" ref="udao"></property>
?</bean>

读书人网 >编程

热点推荐