是一种spring中hibernateTemplat版本的解耦实现。
from:http://www.javaeye.com/topic/47670?page=1
**********************
DaoSupport.java
**********************
public interface DaoSupport {
/**
* 插入一个值对象。
* @param vo 值对象
* @return 已执行插入操作的值对象的主键值
*/
public Serializable insert(Object vo);
/**
* 更新一个值对象,如果值对象在数据库中不存在,则执行插入操作。
* @param vo
*/
public void update(Object vo);
/**
* 批量更新一组值对象
* @param list 值对象列表
*/
public void update(List list);
/**
* 删除一个值对象
* @param vo 值对象
*/
public void delete(Object vo);
/**
* 用主键值删除一个值对象
* @param c 值对象的类
* @param s 主键值
*/
public void delete(Class c, Serializable s);
/**
* 批量删除一组值对象
* @param list 值对象列表
*/
public void delete(List list);
/**
* 根据条件查询数据,<b>注意</b>,该方法之支持单一表的查询
* @param selectClause 查询语句中from之前的部分(包括select),如果是<b>select *</b>则不写,为null
* @param className 值对象的类名
* @param properties 查询条件的属性名列表
* @param operators 查询条件的操作符列表,如果查询条件中存在不为<b>=</b>的操作符,需要填写该列表,否则为null
* @param values 查询条件的值列表,该列表应当与属性列表一一对应
* @param firstRow 返回查询结果的起始行,如果不需要,则设置为0
* @param maxRows 返回查询结果的最大行数,如果不需要,则设置为0
* @return 查询结果的列表
*/
public List query(String selectClause,String className,String[] properties,String[] operators, Object[] values,int firstRow,int maxRows);
/**
* 根据主键值得到一个值对象
* @param c 值对象的类
* @param s 主键值
* @return 值对象
*/
public Object load(Class c, Serializable s);
}
**********************************
DaoSupportHibernate3Imp .java
**********************************
public class DaoSupportHibernate3Imp extends HibernateDaoSupport implements DaoSupport {
private static final Log log = LogFactory.getLog(DaoSupportHibernate3Imp.class);
/* (non-Javadoc)
* @see com.htxx.service.dao.DaoSupport#insert(java.lang.Object)
*/
public Serializable insert(Object vo) {
log.debug("insert "+getClassName(vo)+" instance...");
try{
return this.getHibernateTemplate().save(vo);
} catch (RuntimeException re) {
log.error("insert failed!", re);
throw re;
}
}
/* (non-Javadoc)
* @see com.htxx.service.dao.DaoSupport#update(java.lang.Object)
*/
public void update(Object vo) {
log.debug("update "+getClassName(vo)+" instance...");
try{
this.getHibernateTemplate().saveOrUpdate(vo);
log.debug("update successful!");
} catch (RuntimeException re) {
log.error("update failed!", re);
throw re;
}
}
/* (non-Javadoc)
* @see com.htxx.service.dao.DaoSupport#update(java.util.List)
*/
public void update(final List list) {
log.debug("update with list!");
try{
this.getHibernateTemplate().saveOrUpdateAll(list);
} catch (RuntimeException re) {
log.error("update failed!", re);
throw re;
}
}
/* (non-Javadoc)
* @see com.htxx.service.dao.DaoSupport#delete(java.lang.Object)
*/
public void delete(Object vo) {
log.debug("delete "+getClassName(vo)+" instance...");
try{
this.getHibernateTemplate().delete(vo);
log.debug("delete successful!");
} catch (RuntimeException re) {
log.error("delete failed!", re);
throw re;
}
}
/* (non-Javadoc)
* @see com.htxx.service.dao.DaoSupport#delete(java.lang.Class, java.io.Serializable)
*/
public void delete(Class c,Serializable s) {
Object vo = this.load(c, s);
this.delete(vo);
}
/* (non-Javadoc)
* @see com.htxx.service.dao.DaoSupport#delete(java.util.List)
*/
public void delete(List list){
log.debug("delete with a list.");
try{
if(list==null){throw new RuntimeException("值对象列表不能为null!");}
this.getHibernateTemplate().deleteAll(list);
} catch (RuntimeException re) {
log.error("delete failed!", re);
throw re;
}
}
/* (non-Javadoc)
* @see com.htxx.service.dao.DaoSupport#load(java.lang.Class, java.io.Serializable)
*/
public Object load(Class c, Serializable s) {
log.debug("load "+getClassName(c)+" instance with id: "+s);
try{
if(c==null){throw new RuntimeException("类不能为null!");}
if(s==null){throw new RuntimeException("主键值不能为null!");}
return this.getHibernateTemplate().load(c, s);
} catch (RuntimeException re) {
log.error("load failed!", re);
throw re;
}
}
/* (non-Javadoc)
* @see com.htxx.service.dao.DaoSupport#query(java.lang.String, java.lang.String, java.lang.String[], java.lang.String[], java.lang.Object[], int, int)
*/
public List query(final String selectClause, final String className, final String[] propertyNames,
final String[] operators, final Object[] values, final int firstRow, final int maxRows) {
log.debug("query "+className+" instance with properties: ");
try{
return (List) this.getHibernateTemplate().execute(
new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
if(className==null||className.equals("")){throw new RuntimeException("类名不能为空!");}
String Hql = selectClause==null?"":selectClause + "from " + className + " as model ";
Query query = null;
if(propertyNames!=null&&propertyNames.length>0&&values!=null&&values.length>0){
if(propertyNames.length!=values.length){throw new RuntimeException("条件列表与值列表不对应!");}
if(operators!=null&&propertyNames.length!=operators.length){throw new RuntimeException("条件列表与操作符列表不对应!");}
String where = "";
for(int i=0;i<=propertyNames.length-1;i++){
if("".equals(where)){where="where ";}
else{where +="and ";}
where += "model."+propertyNames[i]+(operators==null||operators[i]==null?"=":operators[i])+"? ";
log.debug(propertyNames[i]+(operators==null||operators[i]==null?"=":operators[i])+"? ");
}
Hql += where;
query = session.createQuery(Hql);
for(int i=0;i<=values.length-1;i++){
query.setParameter(i, values[i]);
}
}else{
query = session.createQuery(Hql);
}
if(firstRow>0){
query.setFirstResult(firstRow);
log.debug("first row: "+firstRow);
}
if(maxRows>0){
query.setMaxResults(maxRows);
log.debug("max rows: "+maxRows);
}
return query.list();
}
}
);
} catch (RuntimeException re) {
log.error("query failed!", re);
throw re;
}
}
private String getClassName(String className){
return className.substring(className.lastIndexOf('.')+1);
}
private String getClassName(Object obj){
return obj==null?"":getClassName(obj.getClass().getName());
}
}
*******************************
DaoSupportHibernateImp .java
*******************************
/**
* 接口DaoSupport的Hibernate2的实现
* @see com.htxx.service.dao.DaoSupport
*/
public class DaoSupportHibernateImp extends HibernateDaoSupport implements DaoSupport {
private static final Log log = LogFactory.getLog(DaoSupportHibernateImp.class);
/* (non-Javadoc)
* @see com.htxx.service.dao.DaoSupport#insert(java.lang.Object)
*/
public Serializable insert(Object vo) {
log.debug("insert "+getClassName(vo)+" instance...");
try{
if(vo==null){throw new RuntimeException("值对象不能为null!");}
return this.getHibernateTemplate().save(vo);
} catch (RuntimeException re) {
log.error("insert failed!", re);
throw re;
}
}
/* (non-Javadoc)
* @see com.htxx.service.dao.DaoSupport#update(java.lang.Object)
*/
public void update(Object vo) {
log.debug("update "+getClassName(vo)+" instance...");
try{
if(vo==null){throw new RuntimeException("值对象不能为null!");}
this.getHibernateTemplate().saveOrUpdate(vo);
log.debug("update successful!");
} catch (RuntimeException re) {
log.error("update failed!", re);
throw re;
}
}
/* (non-Javadoc)
* @see com.htxx.service.dao.DaoSupport#update(java.util.List)
*/
public void update(final List list) {
log.debug("update with list!");
try{
if(list==null){throw new RuntimeException("值对象列表不能为null!");}
this.getHibernateTemplate().execute(
new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
for(Iterator iter = list.iterator(); iter.hasNext();){
Object vo = iter.next();
if(vo==null){session.update(vo);}
}
return null;
}
}
);
} catch (RuntimeException re) {
log.error("update failed!", re);
throw re;
}
}
/* (non-Javadoc)
* @see com.htxx.service.dao.DaoSupport#delete(java.lang.Object)
*/
public void delete(Object vo) {
log.debug("delete "+getClassName(vo)+" instance...");
try{
if(vo==null){throw new RuntimeException("值对象不能为null!");}
this.getHibernateTemplate().delete(vo);
log.debug("delete successful!");
} catch (RuntimeException re) {
log.error("delete failed!", re);
throw re;
}
}
/* (non-Javadoc)
* @see com.htxx.service.dao.DaoSupport#delete(java.lang.Class, java.io.Serializable)
*/
public void delete(Class c,Serializable s) {
Object vo = this.load(c, s);
this.delete(vo);
}
/* (non-Javadoc)
* @see com.htxx.service.dao.DaoSupport#delete(java.util.List)
*/
public void delete(List list){
log.debug("delete with a list.");
try{
if(list==null){throw new RuntimeException("值对象列表不能为null!");}
this.getHibernateTemplate().deleteAll(list);
} catch (RuntimeException re) {
log.error("delete failed!", re);
throw re;
}
}
/* (non-Javadoc)
* @see com.htxx.service.dao.DaoSupport#load(java.lang.Class, java.io.Serializable)
*/
public Object load(Class c, Serializable s) {
log.debug("load "+getClassName(c)+" instance with id: "+s);
try{
if(c==null){throw new RuntimeException("类不能为null!");}
if(s==null){throw new RuntimeException("主键值不能为null!");}
return this.getHibernateTemplate().load(c, s);
} catch (RuntimeException re) {
log.error("load failed!", re);
throw re;
}
}
/* (non-Javadoc)
* @see com.htxx.service.dao.DaoSupport#query(java.lang.String, java.lang.String, java.lang.String[], java.lang.String[], java.lang.Object[], int, int)
*/
public List query(final String selectClause, final String className, final String[] propertyNames,
final String[] operators, final Object[] values, final int firstRow, final int maxRows) {
log.debug("query "+className+" instance with properties: ");
try{
return (List) this.getHibernateTemplate().execute(
new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
if(className==null||className.equals("")){throw new RuntimeException("类名不能为空!");}
String Hql = selectClause==null?"":selectClause + "from " + className + " as model ";
Query query = null;
if(propertyNames!=null&&propertyNames.length>0&&values!=null&&values.length>0){
if(propertyNames.length!=values.length){throw new RuntimeException("条件列表与值列表不对应!");}
if(operators!=null&&propertyNames.length!=operators.length){throw new RuntimeException("条件列表与操作符列表不对应!");}
String where = "";
for(int i=0;i<=propertyNames.length-1;i++){
if("".equals(where)){where="where ";}
else{where +="and ";}
where += "model."+propertyNames[i]+(operators==null||operators[i]==null?"=":operators[i])+"? ";
log.debug(propertyNames[i]+(operators==null||operators[i]==null?"=":operators[i])+"? ");
}
Hql += where;
query = session.createQuery(Hql);
for(int i=0;i<=values.length-1;i++){
query.setParameter(i, values[i]);
}
}else{
query = session.createQuery(Hql);
}
if(firstRow>0){
query.setFirstResult(firstRow);
log.debug("first row: "+firstRow);
}
if(maxRows>0){
query.setMaxResults(maxRows);
log.debug("max rows: "+maxRows);
}
return query.list();
}
}
);
} catch (RuntimeException re) {
log.error("query failed!", re);
throw re;
}
}
private String getClassName(String className){
return className.substring(className.lastIndexOf('.')+1);
}
private String getClassName(Object obj){
return obj==null?"":getClassName(obj.getClass().getName());
}
}
*******************************************
ResultSet .java
*******************************************
/**
*
* The result of query
*/
public class ResultSet implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1375187828856315635L;
private Collection collection; //数据集
private int totalRows; //总共记录数
private int totalPages; //总共页数
private int page; //当前页数
private int pageSize; //每页记录数
/**
* @return the totalPages
*/
public int getTotalPages() {
return totalPages;
}
/**
* @param totalPages the totalPages to set
*/
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}
/**
* @return Returns the collection.
*/
public Collection getCollection() {
return collection;
}
/**
* @param collection The collection to set.
*/
public void setCollection(Collection collection) {
this.collection = collection;
}
/**
* @return Returns the page.
*/
public int getPage() {
return page;
}
/**
* @param page The page to set.
*/
public void setPage(int page) {
this.page = page;
}
/**
* @return Returns the pageSize.
*/
public int getPageSize() {
return pageSize;
}
/**
* @param pageSize The pageSize to set.
*/
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
/**
* @return Returns the totalRows.
*/
public int getTotalRows() {
return totalRows;
}
/**
* @param totalRows The totalRows to set.
*/
public void setTotalRows(int totalRows) {
this.totalRows = totalRows;
}
public ResultSet(Collection co,int totalRows,int page,int pageSize){
if(pageSize==0){pageSize = totalRows;}
this.setCollection(co);
this.setTotalRows(totalRows);
this.setTotalPages(totalRows/pageSize);
this.setPage(page);
this.setPageSize(pageSize);
}
public ResultSet(Collection co){
this.setCollection(co);
this.setTotalRows(co.size());
this.setTotalPages(1);
this.setPage(1);
this.setPageSize(co.size());
}
}
*********************************************
Condition .java
*********************************************
/**
* 携带查询所使用的查询条件
* @see com.htxx.service.dao.BasicDao
*/
public class Condition {
//Fields
private String[] properties;
private String[] operators;
private Object[] values;
private Integer page;
private Integer size;
//Constructors
/** default constructor */
public Condition(){}
/** minimal constructor */
public Condition(String[] properties, Object[] values){
this.properties = properties;
this.values = values;
}
/** full constructor */
public Condition(String[] properties, String[] operators, Object[] values){
this.properties = properties;
this.operators = operators;
this.values = values;
}
/**
* @return the operators
*/
public String[] getOperators() {
return operators;
}
/**
* @param operators the operators to set
*/
public void setOperators(String[] operators) {
this.operators = operators;
}
/**
* @return the properties
*/
public String[] getProperties() {
return properties;
}
/**
* @param properties the properties to set
*/
public void setProperties(String[] properties) {
this.properties = properties;
}
/**
* @return the values
*/
public Object[] getValues() {
return values;
}
/**
* @param values the values to set
*/
public void setValues(Object[] values) {
this.values = values;
}
/**
* @return the page
*/
public Integer getPage() {
return page;
}
/**
* @param page the page to set
*/
public void setPage(Integer page) {
this.page = page;
}
/**
* @return the size
*/
public Integer getSize() {
return size;
}
/**
* @param size the size to set
*/
public void setSize(Integer size) {
this.size = size;
}
}
****************************************
BasicDao .java
****************************************
public abstract class BasicDao {
private DaoSupport daoSupport = null;
/**
* @return the daoSupport
*/
public DaoSupport getDaoSupport() {
return daoSupport;
}
/**
* @param daoSupport the daoSupport to set
*/
public void setDaoSupport(DaoSupport daoSupport) {
this.daoSupport = daoSupport;
}
public void insert(Object vo){
daoSupport.insert(vo);
}
public void update(Object vo){
daoSupport.update(vo);
}
public void delete(Object vo){
daoSupport.delete(vo);
}
public void delete(Class c,Serializable s){
daoSupport.delete(c, s);
}
public void delete(String className, Condition condition){
List list = daoSupport.query("", className, condition.getProperties(), condition.getOperators(),
condition.getValues(), 0, 0);
daoSupport.delete(list);
}
public Object load(Class c,Serializable s){
return daoSupport.load(c, s);
}
public int getCount(String className,String[] propertyNames, String[] operators, Object[] values){
List list = daoSupport.query("select count(*)", className, propertyNames, operators, values, 0, 0);
return ((Integer)list.get(0)).intValue();
}
public int getCount(String className, Condition condition){
return this.getCount(className, condition.getProperties(), condition.getOperators(),
condition.getValues());
}
public ResultSet query(String className,String[] propertyNames, String[] operators, Object[] values,
int page, int size){
List list = daoSupport.query(null, className, propertyNames, operators, values, (page-1)*size, size);
int count = 0;
if(page > 0){
count = this.getCount(className, propertyNames, operators, values);
}else{
count = list.size();
}
return new ResultSet(list,count,page,size);
}
public ResultSet query(String className, Condition condition){
if(condition==null){
return this.query(className, null, null, null, 0, 0);
}
return this.query(className, condition.getProperties(), condition.getOperators(), condition.getValues(),
condition.getPage()==null ? 0 : condition.getPage().intValue(),
condition.getSize()==null ? 0 : condition.getSize().intValue());
}
}
*********************************************
applicationContext-hibernate.xml
*********************************************
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="salaryDS"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url">
<value>jdbc:oracle:thin:@192.168.5.17:1521:hxzfjc</value>
</property>
<property name="username">
<value>fan</value>
</property>
<property name="password">
<value>111111</value>
</property>
</bean>
<!--Hibernate SessionFatory-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="salaryDS"/>
<property name="mappingDirectoryLocations">
<list>
<value>classpath:com/htxx/salary/model</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<!--prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>
<prop key="hibernate.cache.provider_class">${hibernate.cache.provider_class}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.use_sql_comments">${hibernate.use_sql_comments}</prop> -->
</props>
</property>
</bean>
<!--Hibernate TransactionManager-->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="defaultTxAttributes"
class="org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource">
<property name="properties">
<props>
<prop key="create*">PROPAGATION_REQUIRED</prop>
<prop key="modify*">PROPAGATION_REQUIRED</prop>
<prop key="remove*">PROPAGATION_REQUIRED</prop>
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<bean id="InvoiceTxAttributes"
class="org.springframework.transaction.interceptor.NameMatchTransactionAttributeSource">
<property name="properties">
<props>
<prop key="create*">PROPAGATION_REQUIRED</prop>
<prop key="modify*">PROPAGATION_REQUIRED</prop>
<prop key="remove*">PROPAGATION_REQUIRED</prop>
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="accountIn">PROPAGATION_REQUIRED</prop>
<prop key="accountOut">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_SUPPORTS</prop>
</props>
</property>
</bean>
</beans>
*****************************************************
applicationContext-dao .xml
*****************************************************
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="daoSupportHibernate" class="com.htxx.service.dao.DaoSupportHibernate3Imp">
<property name="sessionFactory"><ref bean="sessionFactory"/></property>
</bean>
<bean id="departmentDao" class="com.htxx.salary.employee.dao.imp.DepartmentDaoImp">
<property name="daoSupport"><ref bean="daoSupportHibernate"/></property>
</bean>
<bean id="employeeDao" class="com.htxx.salary.employee.dao.imp.EmployeeDaoImp">
<property name="daoSupport"><ref bean="daoSupportHibernate"/></property>
</bean>
<bean id="hourlyPaymentDao" class="com.htxx.salary.employee.dao.imp.HourlyPaymentDaoImp">
<property name="daoSupport"><ref bean="daoSupportHibernate"/></property>
</bean>
<bean id="salariedPaymentDao" class="com.htxx.salary.employee.dao.imp.SalariedPaymentDaoImp">
<property name="daoSupport"><ref bean="daoSupportHibernate"/></property>
</bean>
<bean id="paymentForSaleDao" class="com.htxx.salary.employee.dao.imp.SalesPaymentDaoImp">
<property name="daoSupport"><ref bean="daoSupportHibernate"/></property>
</bean>
<bean id="hoursOfWorkingDao" class="com.htxx.salary.working.dao.imp.HoursOfWorkingDaoImp">
<property name="daoSupport"><ref bean="daoSupportHibernate"/></property>
</bean>
<bean id="salariedWorkingDao" class="com.htxx.salary.working.dao.imp.SalariedWorkingDaoImp">
<property name="daoSupport"><ref bean="daoSupportHibernate"/></property>
</bean>
<bean id="saleOfWorkingDao" class="com.htxx.salary.working.dao.imp.SaleOfWorkingDaoImp">
<property name="daoSupport"><ref bean="daoSupportHibernate"/></property>
</bean>
<bean id="payingDao" class="com.htxx.salary.paying.dao.imp.PayingDaoImp">
<property name="daoSupport"><ref bean="daoSupportHibernate"/></property>
</bean>
</beans>