Spring+Hibernate整合
在進行整合前,我認為將Hibernate的配置整合到Spring的配置中,由Spring進行管理,由Hibernate進行對數據庫的操作。
后來在網上找了一些整合的方法,但是整合都失敗了,因為我的Hibernate的版本是5,所以有些包被集成進其他包,在Spring的xml文件中配置,是找不到那個包的,而且我也不清楚Hibernate5將這個包放在哪里,或者未來還將有多少類似的事情發生,所以還是重新下載Hibernate3.3來用。
項目目錄如下:
下載好了Hibernate3.3后,我們開始整合Spring和Hibernate!
1. 建立一個User Library,向其中導入Hibernate需要用到的jar包。
在這里,我們一定要注意,寧可少導包,報錯后按照提示進行導包,也不要多導,否則會出問題。以下是使用Hibernate3.3需要導入的包:
a) 連接mysql的jar包,我是為了方便直接導入了。
b) hibernate-distribution-3.3.2.GA目錄下的hibernate3.jar。
這是Hibernate3.3的核心包
c) 將hibernate-distribution-3.3.2.GA\lib\required目錄下的6個jar包全部導入。
d) 因為我們要使用注解,就需要添加和注解有關的jar包,需要下載
hibernate-annotation-3.4.0.GA的所有jar包。
將hibernate-annotations-3.4.0.GA目錄下的hibernate-annotations.jar導入。
e) 將hibernate-annotations-3.4.0.GA\hibernate-annotations-3.4.0.GA\lib目錄下的ejb3-persistence.jar以及hibernate-sommons-annotations.jar導入。
f) 最后需要下載slf4j-1.5.8(一定要和上面導入的slf4j-api-1.5.8.jar版本相同)將目錄下的slf4j-nop-1.5.8.jar導入。
至此,Hibernate需要的包全部導入了。
2. 建立Spring的User Library。
需要的包如下:還是注意,寧可多導,不能少導。
3. 先建立個實體類
建立實體類的時候,實體類名稱盡量不要與Mysql的關鍵字重復,否則容易引起沖突。我在此建立一個Student實體類。在這里加上@Entity,@Id,@generatedValue注解。

1 package com.spring_hibernate.model; 2 3 import javax.persistence.Entity; 4 import javax.persistence.GeneratedValue; 5 import javax.persistence.Id; 6 7 @Entity 8 public class Student { 9 private int id; 10 private String name; 11 private int age; 12 13 @Id 14 @GeneratedValue 15 public int getId() { 16 return id; 17 } 18 public void setId(int id) { 19 this.id = id; 20 } 21 public String getName() { 22 return name; 23 } 24 public void setName(String name) { 25 this.name = name; 26 } 27 public int getAge() { 28 return age; 29 } 30 public void setAge(int age) { 31 this.age = age; 32 } 33 @Override 34 public String toString() { 35 return "Student [id=" + id + ", name=" + name + ", age=" + age + "]"; 36 } 37 public Student(int id, String name, int age) { 38 super(); 39 this.id = id; 40 this.name = name; 41 this.age = age; 42 } 43 public Student() { 44 super(); 45 } 46 47 48 }
4. 寫DAO接口
我們寫一個StudentDao接口,其中有一個方法save(Student student)用於向數據庫存儲學生數據。

1 package com.spring_hibernate.dao; 2 import com.spring_hibernate.model.Student; 3 4 public interface StudentDao { 5 public void save(Student student); 6 }
5. 配置文件
在寫Dao實現前,我們先把配置文件搞定,我們只需要寫關於Spring的配置文件就可以,讓Spring控制SessionFactory,在其中將Hibernate集成進去。建立一個beans.xml文件:

1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:aop="http://www.springframework.org/schema/aop" 6 xmlns:tx="http://www.springframework.org/schema/tx" 7 xsi:schemaLocation="http://www.springframework.org/schema/beans 8 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 9 http://www.springframework.org/schema/context 10 http://www.springframework.org/schema/context/spring-context-2.5.xsd 11 http://www.springframework.org/schema/aop 12 http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 13 http://www.springframework.org/schema/tx 14 http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> 15 <context:annotation-config /> 16 <context:component-scan base-package="com.spring_hibernate" /> 17 18 <!-- 用Properties文件讀取數據庫連接信息 --> 19 <bean 20 class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 21 <property name="locations"> 22 <value>classpath:jdbc.properties</value> 23 </property> 24 </bean> 25 26 <!-- 數據源定義 --> 27 <bean id="dataSource" destroy-method="close" 28 class="org.apache.commons.dbcp.BasicDataSource"> 29 <property name="driverClassName" value="${jdbc.driverClassName}" /> 30 <property name="url" value="${jdbc.url}" /> 31 <property name="username" value="${jdbc.username}" /> 32 <property name="password" value="${jdbc.password}" /> 33 </bean> 34 35 <!-- 最重要的配置:SessionFactory的配置 這里是用注解的SessionFactory --> 36 <bean id="sessionFactory" 37 class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> 38 <!-- 注入數據源 --> 39 <property name="dataSource" ref="dataSource" /> 40 <!-- 注入實體類 --> 41 <property name="annotatedClasses"> 42 <list> 43 <value>com.spring_hibernate.model.Student</value> 44 </list> 45 </property> 46 <!-- 將Hibernate的配置信息集成進來 --> 47 <property name="hibernateProperties"> 48 <props> 49 <!-- 方言:這里是Mysql --> 50 <prop key="hibernate.dialect"> 51 org.hibernate.dialect.MySQLDialect 52 </prop> 53 <!-- 是否顯示sql語句 --> 54 <prop key="hibernate.show_sql">true</prop> 55 <!-- sql語句按規范顯示 --> 56 <prop key="hibernate.format_sql">true</prop> 57 <!-- 自動對表的操作 --> 58 <prop key="hibernate.hbm2ddl.auto">update</prop> 59 </props> 60 </property> 61 </bean> 62 </beans>
6. StudentDao的實現類
我們建立一個StudentDao的實現類StudentDaoImpl。因為在這里要進行對數據庫操作的實現,所以要用到SessionFactory,我們將SessionFactory作為StudentDaoImpl的一個私有成員。然后實現StudentDao的save方法,用Hibernate的方式進行存儲。這里要用到@Repository(Dao層),@Resource(在setSessionFactory方法上用到,對SessionFactory進行注入)

1 package com.spring_hibernate.daoImpl; 2 3 import javax.annotation.Resource; 4 5 import org.hibernate.Session; 6 import org.hibernate.SessionFactory; 7 import org.springframework.stereotype.Repository; 8 9 import com.spring_hibernate.dao.StudentDao; 10 import com.spring_hibernate.model.Student; 11 12 @Repository 13 public class StudentDaoImpl implements StudentDao{ 14 private SessionFactory sessionFactory; 15 16 public SessionFactory getSessionFactory() { 17 return sessionFactory; 18 } 19 20 @Resource 21 public void setSessionFactory(SessionFactory sessionFactory) { 22 this.sessionFactory = sessionFactory; 23 } 24 25 @Override 26 public void save(Student student) { 27 Session session = sessionFactory.openSession(); 28 session.beginTransaction(); 29 session.save(student); 30 session.getTransaction().commit(); 31 session.close(); 32 System.out.println("saved!"); 33 } 34 }
7. StudentService類
在StudentService中,將StudentDao作為私有成員。添加get/set方法。用到@Service(Service層) @Resource(自動注入studentDao的實現類)再添加一個add方法,調用StudentDao的save方法。

1 package com.spring_hibernate.service; 2 3 import javax.annotation.Resource; 4 import org.springframework.stereotype.Service; 5 import com.spring_hibernate.dao.StudentDao; 6 import com.spring_hibernate.model.Student; 7 8 @Service 9 public class StudentService { 10 private StudentDao studentDao; 11 12 public StudentDao getStudentDao() { 13 return studentDao; 14 } 15 @Resource 16 public void setStudentDao(StudentDao studentDao) { 17 this.studentDao = studentDao; 18 } 19 20 public void add(Student student){ 21 studentDao.save(student); 22 } 23 }
8. ServiceTest類
新建一個test源目錄,書寫ServiceTest類。

1 package com.spring_hibernate.test; 2 import org.junit.Test; 3 import org.springframework.context.support.ClassPathXmlApplicationContext; 4 import com.spring_hibernate.model.Student; 5 import com.spring_hibernate.service.StudentService; 6 7 public class ServiceTest { 8 @Test 9 public void testService(){ 10 ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); 11 StudentService service = (StudentService)ctx.getBean("studentService"); 12 service.add(new Student(0, "li", 20)); 13 ctx.destroy(); 14 } 15 }
如果我們用到了properties文件保存數據庫連接信息,我們要在src下添加jdbc. properties。
如果我們要顯示hibernate日志信息,log4j.properties也加在src目錄下。
成功運行:
看一下數據庫:表是自動創建的
成功添加數據!
請尊重勞動成果,轉載請注明鏈接。