你的位置:首页 > ASP.net教程

[ASP.net教程]Spring与Hibernate整合之通用Dao的实现


在上一篇文章中写了如何直接利用HibernateTemplate进行数据库操作,但在一般的项目中很少直接得到HibernateTemplate的
Bean对象从而操作数据库的,下面就简要介绍一下实现通用的数据库操作对象Dao类:

1、最基本的数据库操作接口BaseDao<T>:

 1 import java.io.Serializable; 2 import java.util.List; 3  4 public interface BaseDao<T> { 5    6   Serializable save (T entity); 7    8   void delete (T entity); 9   void delete (Class<T> clazz,Serializable id);10   11   void update(T entity);12   13   T get(Class<T> clazz,Serializable id);14   15   List<T> findAll(Class<T> clazz);16   17   List<T> findAll(Class<T> clazz,String where);18   19   20 }

 

2、实现BaseDao<T>的实现类BaseDaoImpl<T>:

 1 import java.io.Serializable; 2 import java.util.List; 3  4 import org.springframework.orm.hibernate3.support.HibernateDaoSupport; 5  6 public class BaseDaoImpl<T> extends HibernateDaoSupport implements BaseDao<T>{ 7  8   @Override 9   public Serializable save(T entity) {10     // TODO Auto-generated method stub11     return getHibernateTemplate().save(entity);12   }13 14   @Override15   public void delete(T entity) {16     // TODO Auto-generated method stub17     getHibernateTemplate().delete(entity);18     19   }20 21   @Override22   public void delete(Class clazz, Serializable id) {23     // TODO Auto-generated method stub24     delete(get(clazz,id));25     26   }27 28   @Override29   public void update(T entity) {30     // TODO Auto-generated method stub31     getHibernateTemplate().saveOrUpdate(entity);32     33   }34 35   @Override36   public T get(Class clazz, Serializable id) {37     // TODO Auto-generated method stub38     return (T) getHibernateTemplate().get(clazz, id);39   }40 41   @Override42   public List<T> findAll(Class clazz) {43     // TODO Auto-generated method stub44     return (List<T>) getHibernateTemplate().find("select en from "+clazz.getSimpleName()+" en");45   }46 47   @Override48   public List findAll(Class clazz, String where) {49     // TODO Auto-generated method stub50     return getHibernateTemplate().find("select en from "+clazz.getSimpleName()+" en where "+where);51   }52 53 }


3、实体User:

 1 import java.util.Date; 2  3 import javax.persistence.Column; 4 import javax.persistence.Entity; 5 import javax.persistence.GeneratedValue; 6 import javax.persistence.GenerationType; 7 import javax.persistence.Id; 8 import javax.persistence.Temporal; 9 import javax.persistence.TemporalType;10 11 @Entity12 public class User {13 14   @Id15   @Column(name="user_id")16   @GeneratedValue(strategy=GenerationType.IDENTITY)17   private Integer id;18   @Column(name="user_name")19   private String name;20   private String pass;21   @Temporal(TemporalType.DATE)22   private Date birth;23   24   25   26   public User() {27     28   }29   30   31   public User( String name, String pass, Date birth) {32     super();33     this.name = name;34     this.pass = pass;35     this.birth = birth;36   }37   38   public Integer getId() {39     return id;40   }41 42 43   public void setId(Integer id) {44     this.id = id;45   }46 47 48   public String getName() {49     return name;50   }51   public void setName(String name) {52     this.name = name;53   }54   public String getPass() {55     return pass;56   }57   public void setPass(String pass) {58     this.pass = pass;59   }60 61 62   public Date getBirth() {63     return birth;64   }65 66 67   public void setBirth(Date birth) {68     this.birth = birth;69   }70   71   72 }


4、针对User类的数据库操作Dao的接口,由于继承了BaseDao<User>,基本的函数接口也不用再写了,空的接口是为了日后的扩展:

1 import com.csu.comm.dao.BaseDao;2 import com.csu.domain.User;3 4 public interface UserDao extends BaseDao<User>{5 6 }


5、实现了BaseDao<User>的类UserDaoImpl,也因为继承了BaseDaoImpl<User>,基本的操作已经都实现了,空体也是为了日后的扩展:

 1 import java.io.Serializable; 2 import java.util.List; 3  4 import com.csu.comm.dao.BaseDaoImpl; 5 import com.csu.dao.UserDao; 6 import com.csu.domain.User; 7  8 public class UserDaoImpl extends BaseDaoImpl<User> implements UserDao { 9 10 11 }


6、c3p0数据库连接池所需要的数据库配置信息,放置在jdbc.properties文件中,这样也方便日后修改只需要改动属性文件,
而不需要改动配置文件:

1 user=root2 password=78903 driverClass=com.mysql.jdbc.Driver4 jdbcUrl=jdbc:mysql://localhost:3306/spring5 maxPoolSize=2006 minPoolSize=27 initialPoolSize=2


7、hibernate配置文件hibernate.cfg.

 1 <? 2 <!DOCTYPE hibernate-configuration PUBLIC 3     "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 4     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 5  6 <hibernate-configuration> 7  8   <session-factory> 9     <!-- hibernate 所需的配置信息 -->10     <property name="show_sql">true</property>11     <property name="dialect">org.hibernate.dialect.MySQLDialect</property><!--方言-->12     <property name="format_sql">true</property>13     <property name="hbm2ddl.auto">update</property>14     15     <!-- hibernate 指定映射类 -->16     <mapping class="com.csu.domain.User"/>17     18   </session-factory>19   20 </hibernate-configuration>


8、spring的配置文件:

 1 <? 2  3 <!-- 整个Spring 文件的根元素就是beans --> 4 <beans  5  6  7  8    9   xsi:schemaLocation="http://www.springframework.org/schema/beans10     http://www.springframework.org/schema/beans/spring-beans.xsd11     12     http://www.springframework.org/schema/util13     http://www.springframework.org/schema/util/spring-util.xsd14     15     http://www.springframework.org/schema/context16     http://www.springframework.org/schema/context/spring-context.xsd17     ">18 19    <!-- *****************配置数据源*********************** -->20    21    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">22    23      <property name="locations">24        <!-- 列出需要读取的属性文件 -->25        <list>26          <value>classpath:jdbc.properties</value>27        </list>28      </property>29        30    </bean>31      32    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"33      p:user="${user}"34      p:password="${password}"35      p:driver36      p:jdbcUrl="${jdbcUrl}"37      p:maxPoolSize="${maxPoolSize}"38      p:minPoolSize="${minPoolSize}"39      p:initialPoolSize="${initialPoolSize}"40    />41    <!-- *****************配置数据源*********************** -->42   43   <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"44   p:dataSource-ref="dataSource"45   p:configLocation="classpath:hibernate.cfg.46   />47   48   <!--因为UserDaoImpl继承了BaseDaoImpl<T>, BaseDaoImpl<T> 继承了 HibernateDaoSupport,HibernateDaoSupport有setSessionFactory函数-->49   <bean id="userDao" class="com.csu.dao.impl.UserDaoImpl"50     p:sessionFactory-ref="sessionFactory"51   52   />53   54 </beans>


10、测试主类:

 1 import java.sql.SQLException; 2 import java.util.Date; 3 import java.util.List; 4  5 import org.hibernate.FlushMode; 6 import org.hibernate.HibernateException; 7 import org.hibernate.Session; 8 import org.springframework.context.ApplicationContext; 9 import org.springframework.context.support.ClassPath10 import org.springframework.orm.hibernate3.HibernateCallback;11 import org.springframework.orm.hibernate3.HibernateTemplate;12 13 import com.csu.dao.UserDao;14 import com.csu.domain.User;15 16 17 public class SpHiTest {18 19   public static void main(String[] args) {20     ApplicationContext ctx = new ClassPath);21     22     UserDao userDao = ctx.getBean("userDao",UserDao.class);23     List<User> users = userDao.findAll(User.class);24     for(Object u : users){25       System.out.println(((User) u).getName());26     }27     28   }29 }

 11、结果;