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 stub
11         return getHibernateTemplate().save(entity);
12     }
13 
14     @Override
15     public void delete(T entity) {
16         // TODO Auto-generated method stub
17         getHibernateTemplate().delete(entity);
18         
19     }
20 
21     @Override
22     public void delete(Class clazz, Serializable id) {
23         // TODO Auto-generated method stub
24         delete(get(clazz,id));
25         
26     }
27 
28     @Override
29     public void update(T entity) {
30         // TODO Auto-generated method stub
31         getHibernateTemplate().saveOrUpdate(entity);
32         
33     }
34 
35     @Override
36     public T get(Class clazz, Serializable id) {
37         // TODO Auto-generated method stub
38         return (T) getHibernateTemplate().get(clazz, id);
39     }
40 
41     @Override
42     public List<T> findAll(Class clazz) {
43         // TODO Auto-generated method stub
44         return (List<T>) getHibernateTemplate().find("select en from "+clazz.getSimpleName()+" en");
45     }
46 
47     @Override
48     public List findAll(Class clazz, String where) {
49         // TODO Auto-generated method stub
50         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 @Entity
12 public class User {
13 
14     @Id
15     @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=root
2 password=7890
3 driverClass=com.mysql.jdbc.Driver
4 jdbcUrl=jdbc:mysql://localhost:3306/spring
5 maxPoolSize=200
6 minPoolSize=2
7 initialPoolSize=2


7、hibernate配置文件hibernate.cfg.xml:

 1 <?xml version='1.0' encoding='utf-8'?>
 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 <?xml version="1.0" encoding="UTF-8"?>
 2 
 3 <!-- 整个Spring 文件的根元素就是beans -->
 4 <beans xmlns="http://www.springframework.org/schema/beans"
 5 xmlns:p="http://www.springframework.org/schema/p"
 6 xmlns:util="http://www.springframework.org/schema/util"
 7 xmlns:context="http://www.springframework.org/schema/context"
 8     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 9     xsi:schemaLocation="http://www.springframework.org/schema/beans
10         http://www.springframework.org/schema/beans/spring-beans.xsd
11         
12         http://www.springframework.org/schema/util
13         http://www.springframework.org/schema/util/spring-util.xsd
14         
15         http://www.springframework.org/schema/context
16         http://www.springframework.org/schema/context/spring-context.xsd
17         ">
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:driverClass="${driverClass}"
36            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.xml"
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.ClassPathXmlApplicationContext;
10 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 ClassPathXmlApplicationContext("beans.xml");
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、结果;

posted @ 2015-09-26 13:55  苏幕遮soft  阅读(772)  评论(0编辑  收藏  举报