java框架篇---spring hibernate整合


在會使用hibernate 和spring框架后 兩個框架的整合就變的相當容易了,

為什么要整合Hibernate?
1、使用Spring的IOC功能管理SessionFactory對象
 LocalSessionFactoryBean
2、使用Spring管理Session對象 
 HibernateTemplate
3、使用Spring的功能實現聲明式的事務管理

第一步:搭建hibernate環境(包括引入hibernate的jar,包配置數據源,建立類和表的映射),為什么這么做。我覺得hibernate是最重要的。因為沒有spring不影響我往數據里面添加記錄。Spring僅僅是一個容器。這就不多說了。

第二步:配置spring的環境(引入jar和寫一個bean.XML的配置信息)

省略了hibernate.cfg.xml文件 全部托管於spring配置文件

在純粹的Hibernate訪問中,應用程序需要手動創建SessionFactory實例,可想而知,這不是一個優秀的策略。在實際開發中,希望以一種聲明式的方式管理SessionFactory實例,直接以配置文件來管理SessionFactory實例,在示范Struts的PlugIn擴展點時,

Spring的IoC容器則提供了更好的管理方式,它不僅能以聲明式的方式配置Session- Factory實例,也可充分利用IoC容器的作用,為SessionFactory注入數據源引用。

下面是Spring配置文件中配置Hibernate SessionFactory的示范代碼:

<?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:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-3.1.xsd
           http://www.springframework.org/schema/aop            
           http://www.springframework.org/schema/aop/spring-aop-3.1.xsd  " default-autowire="byName">
    <context:annotation-config />
    <context:component-scan base-package="com.bjsxt" />

    <!-- 
    也可以使用這種方法 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/myuse" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean>
--> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <value>classpath:jdbc.properties</value> </property> </bean> <bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="annotatedClasses"> <list> <value>com.bjsxt.model.User</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> </beans>

jdbc.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc\:mysql\://localhost\:3306/myuse
jdbc.username=root
jdbc.password=root  

第三步:在spring里面注冊hibernate。

<bean id="txManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
    
<tx:annotation-driven transaction-manager="txManager"/>

在Dao組件中,所有的持久化操作都通過HibernateTemplate實例完成,而HibernateTemplate操作數據庫非常簡潔,大部分CRUD操作都可通過一行代碼解決問題。下面介紹如何通過HibernateTemplate進行持久層訪問。

HibernateTemplate提供了非常多的常用方法來完成基本的操作,比如通常的增加、刪除、修改、查詢等操作,Spring 2.0更增加了對命名SQL查詢的支持,也增加了對分頁的支持。大部分情況下,使用Hibernate的常規用法,就可完成大多數DAO對象的CRUD操作。下面是HibernateTemplate的常用方法簡介:

   ● void delete(Object entity),刪除指定持久化實例。

   ● deleteAll(Collection entities),刪除集合內全部持久化類實例。

   ● find(String queryString),根據HQL查詢字符串來返回實例集合。

   ● findByNamedQuery(String queryName),根據命名查詢返回實例集合。

   ● get(Class entityClass, Serializable id),根據主鍵加載特定持久化類的實例。

   ● save(Object entity),保存新的實例。

   ● saveOrUpdate(Object entity),根據實例狀態,選擇保存或者更新。

   ● update(Object entity),更新實例的狀態,要求entity是持久狀態。

   ● setMaxResults(int maxResults),設置分頁的大小。

下面是一個完整DAO類的源代碼:

測試:

package com.bjsxt.service;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.bjsxt.model.User;

//Dependency Injection
//Inverse of Control
public class UserServiceTest {

    @Test 
    public void testAdd() throws Exception {
        ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
        
        UserService service = (UserService)ctx.getBean("userService");
        System.out.println(service.getClass());
        service.save(new User());
        
        ctx.destroy();
        
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM