Spring+Hibernate泛型DAO的自动注入(例子)

总体架构:
[img]http://dl.iteye.com/upload/attachment/0070/5025/0752a9f3-58de-3e09-abd3-0fe65ccae950.png[/img]

1.定义泛型DAO接口:
package com.integration.framework.dao;

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

/**
* @ClassName:IBaseGenericDAO
* @Description:TODO(IBaseGenericDAO DAO层泛型接口,定义基本的DAO功能 )
* @param <T> 实体类
* @param <PK> 主键类,必须实现Serializable接口
* @author zj
* @date:Jul 9, 2012 1:32:07 PM
* @version V1.0
*/
public abstract interface IBaseGenericDAO<T, PK extends Serializable> {

/**
* 按主键取记录
* @param id 主键值
* @return 记录实体对象,如果没有符合主键条件的记录,则返回null
*/
public abstract T get(PK id);

/**
* 按主键取记录
* @param id 主键值
* @return 记录实体对象,如果没有符合主键条件的记录,则 throw DataAccessException
*/
public abstract T load(PK id);

/**
* 获取全部实体
* @return 返回一个list集合数据
*/
public abstract List<T> loadAll();

/**
* 修改一个实体对象(UPDATE一条记录)
* @param entity 实体对象
*/
public abstract void update(T entity);

/**
* 插入一个实体(在数据库INSERT一条记录)
* @param entity 实体对象
*/
public abstract void save(T entity);

/**
* 增加或更新实体
* @param entity 实体对象
*/
public abstract void saveOrUpdate(T entity);

/**
* 删除指定的实体
* @param entity 实体对象
*/
public abstract void delete(T entity);

}

2.实现IBaseGenericDAO接口的Hibernate的实现类HibernateBaseGenericDAOImpl:

package com.integration.framework.dao.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.integration.framework.dao.IBaseGenericDAO;

/**
* @ClassName:HibernateBaseGenericDAOImpl
* @Description:TODO(HibernateBaseGenericDAOImpl DAO层泛型基类,实现了基本的DAO功能 利用了Spring的HibernateDaoSupport功能)
* @param <T> 实体类
* @param <PK> 主键类,必须实现Serializable接口
* @author zj
* @date:Jul 9, 2012 1:41:37 PM
* @version V1.0
*/
@SuppressWarnings("all")
public class HibernateBaseGenericDAOImpl<T, PK extends Serializable> extends HibernateDaoSupport implements IBaseGenericDAO<T, PK>{

private static Log logger = LogFactory.getLog(HibernateBaseGenericDAOImpl.class);

private Class<T> entityClass;

/**
* 构造方法,根据实例类自动获取实体类类型
*/
public HibernateBaseGenericDAOImpl() {
this.entityClass = null;
Class c = getClass();
Type t = c.getGenericSuperclass();
if (t instanceof ParameterizedType) {
Type[] p = ((ParameterizedType) t).getActualTypeArguments();
this.entityClass = (Class<T>) p[0];
}
}

/*
* (non-Javadoc)
* @see com.integration.framework.dao.IBaseGenericDAO#delete(java.lang.Object)
*/
public void delete(T entity) {
try{
getHibernateTemplate().delete(entity);
}catch(DataAccessException e){
logger.error(e.getMessage(), e);
}
}

/*
* (non-Javadoc)
* @see com.integration.framework.dao.IBaseGenericDAO#get(java.io.Serializable)
*/
public T get(PK id) {
return (T) getHibernateTemplate().get(entityClass, id);
}

/*
* (non-Javadoc)
* @see com.integration.framework.dao.IBaseGenericDAO#load(java.io.Serializable)
*/
public T load(PK id) {
return (T) getHibernateTemplate().load(entityClass, id);
}

/*
* (non-Javadoc)
* @see com.integration.framework.dao.IBaseGenericDAO#loadAll()
*/
public List<T> loadAll() {
return getHibernateTemplate().loadAll(entityClass);
}

/*
* (non-Javadoc)
* @see com.integration.framework.dao.IBaseGenericDAO#save(java.lang.Object)
*/
public void save(T entity) {
try{
getHibernateTemplate().save(entity);
}catch(DataAccessException e){
logger.error(e.getMessage(), e);
}
}

/*
* (non-Javadoc)
* @see com.integration.framework.dao.IBaseGenericDAO#saveOrUpdate(java.lang.Object)
*/
public void saveOrUpdate(T entity) {
try{
getHibernateTemplate().saveOrUpdate(entity);
}catch(DataAccessException e){
logger.error(e.getMessage(), e);
}
}

/*
* (non-Javadoc)
* @see com.integration.framework.dao.IBaseGenericDAO#update(java.lang.Object)
*/
public void update(T entity) {
try{
getHibernateTemplate().update(entity);
}catch(DataAccessException e){
logger.error(e.getMessage(), e);
}
}
}



3.定义Service泛型接口:

package com.integration.framework.service;

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

/**
* @ClassName:IBaseGenericService
* @Description:TODO(IBaseGenericService Service层泛型接口,定义基本的Service功能)
* @param <T> 实体类
* @param <PK> 主键类,必须实现Serializable接口
* @author zhoujing
* @date:Jul 9, 2012 2:48:56 PM
* @version V1.0
*/
public interface IBaseGenericService<T, PK extends Serializable> {

/**
* 按主键取记录
* @param id 主键值
* @return 记录实体对象,如果没有符合主键条件的记录,则返回null
*/
public abstract T get(PK id);

/**
* 按主键取记录
* @param id 主键值
* @return 记录实体对象,如果没有符合主键条件的记录,则 throw DataAccessException
*/
public abstract T load(PK id);

/**
* 获取全部实体
* @return 返回一个list集合数据
*/
public abstract List<T> loadAll();

/**
* 修改一个实体对象(UPDATE一条记录)
* @param entity 实体对象
*/
public abstract void update(T entity);

/**
* 插入一个实体(在数据库INSERT一条记录)
* @param entity 实体对象
*/
public abstract void save(T entity);

/**
* 增加或更新实体
* @param entity 实体对象
*/
public abstract void saveOrUpdate(T entity);

/**
* 删除指定的实体
* @param entity 实体对象
*/
public abstract void delete(T entity);
}


4.实现Service:

package com.integration.framework.service.impl;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.integration.framework.dao.IBaseGenericDAO;
import com.integration.framework.service.IBaseGenericService;

/**
* @ClassName:BaseGenericServiceImpl
* @Description:TODO(这里用一句话描述这个类的作用)
* @author zhoujing
* @date:Jul 9, 2012 5:16:46 PM
* @version V1.0
*/
@Service
@SuppressWarnings("all")
public class BaseGenericServiceImpl<T, PK extends Serializable> implements IBaseGenericService<T, PK> {

@Autowired
private IBaseGenericDAO dao;

public void delete(T entity) {
dao.delete(entity);
}

public T get(PK id) {
return (T)dao.get(id);
}

public T load(PK id) {
return (T) dao.load(id);
}

public List<T> loadAll() {
return dao.loadAll();
}

public void save(T entity) {
dao.save(entity);
}

public void saveOrUpdate(T entity) {
dao.saveOrUpdate(entity);
}

public void update(T entity) {
dao.update(entity);
}

}


5.配置applicationContext:

<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"
default-autowire="byName" default-lazy-init="false">

<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:/db/jdbc.properties</value>
</list>
</property>
</bean>

<!-- c3p0 数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<property name="driverClass" value="${jdbc.driverClassName}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="minPoolSize" value="${c3p0.minPoolSize}"/>
<property name="maxPoolSize" value="${c3p0.maxPoolSize}"/>
<property name="initialPoolSize" value="${c3p0.initialPoolSize}"/>
<property name="maxIdleTime" value="${c3p0.maxIdleTime}"/>
<property name="acquireIncrement" value="${c3p0.acquireIncrement}"/>
<property name="testConnectionOnCheckin" value="${c3p0.testConnectionOnCheckin}"/>
<property name="acquireRetryAttempts" value="${c3p0.acquireRetryAttempts}"/>
<property name="acquireRetryDelay" value="${c3p0.acquireRetryDelay}"/>
<property name="breakAfterAcquireFailure" value="${c3p0.breakAfterAcquireFailure}"/>
<property name="idleConnectionTestPeriod" value="${c3p0.idleConnectionTestPeriod}"/>
<property name="automaticTestTable" value="${c3p0.automaticTestTable}"/>
</bean>

<!-- 配置sessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.generate_statistics">true</prop>
<prop key="hibernate.connection.release_mode">auto</prop>
<prop key="hibernate.autoReconnect">true</prop>

<prop key="query.substitutions">true 1, false 0, yes '1', no '1'</prop>

<prop key="hibernate.jdbc.fetch_size">50</prop>
<prop key="hibernate.jdbc.batch_size">25</prop>
<prop key="hibernate.jdbc.use_scrollable_resultset">true</prop>
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.integration</value>
</list>
</property>
</bean>

<!-- 事务管理 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<tx:advice id="txAdvice" transaction-manager="transactionManager" >
<tx:attributes >
<tx:method name="get*" read-only="true" />
<tx:method name="load*" read-only="true" />
<tx:method name="query*" read-only="true" />
<!-- other methods use the default transaction settings (see below) -->
<tx:method name="*" rollback-for="Exception" />
</tx:attributes >
</tx:advice>

<context:component-scan base-package="com.integration" />

<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
</beans>

6.web.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<display-name>Integration</display-name>
<!-- 指定spring配置文件的位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/context/applicationContext*.xml</param-value>
</context-param>

<!-- ============log4j begin=========-->
<!--for Spring-loading-->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:/log4j.properties</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.util.Log4jConfigListener
</listener-class>
</listener>
<!-- ============log4j end=========-->

<!-- Struts 2 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 自动加载applicationContext -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

</web-app>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值