spring 整合hibernate

1.Spring 要整合hibernate的什么

  1). 由IOC容器来管理Hibernate的sessionFactory

  2).让hibernate使用上Spring的声明式事务

2.整合步骤:

  1).加入hibernate 

    --jar包

    --添加hibernate配置文件:hibernate.cfg.xml

    --编写持久化类对应的.hbm.xml配置文件

  2).加入Spring 

    --Spring jar包

    --加入Spring的配置文件

  3).整合

 

例子:

hibernate.cfg.xml:

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>
    
        <!-- 配置hibernate的基本属性 -->
        <!-- 1.数据源需 配置在IOC容器中,所以此处不需要配置数据源-->
        <!-- 2.关联的.hbm.xml也在IOC配置SessionFactory实例时进行配置 -->
        <!-- 3.配置hibernate的基本属性:方言,sql显示及格式,生成数据表的策略以及二级缓存等 -->
        
                <!-- 指定Hibernate的连接方言 -->
                <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
                <!-- 配置启动应用时,是否根据Hibernate映射自动创建数据表 -->
                <property name="hibernate.hbm2ddl.auto">update</property>
                <!--是否显示SQL-->
                <property name="hibernate.show_sql">true</property>
                <!-- 是否格式化显示SQL -->
                <property name="hibernate.format_sql">true</property>
                
                <!-- 配置hibernate二级缓存相关的属性 -->
</session-factory>
</hibernate-configuration>

持久化类:

Accoount:

package com.sh.entity;

public class Accoount {
    private Integer id;
    private String username;
    private Integer balance;
    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public Integer getBalance() {
        return balance;
    }
    public void setBalance(Integer balance) {
        this.balance = balance;
    }
    
    
}

Book:

package com.sh.entity;

public class Book {
    private Integer id;
    private String bookName;
    private String isbn;
    private Integer price;
    private int stock;
    
    
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getBookName() {
        return bookName;
    }
    public void setBookName(String bookName) {
        this.bookName = bookName;
    }
    public String getIsbn() {
        return isbn;
    }
    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }
    public Integer getPrice() {
        return price;
    }
    public void setPrice(Integer price) {
        this.price = price;
    }
    public int getStock() {
        return stock;
    }
    public void setStock(int stock) {
        this.stock = stock;
    }
    
    
}

持久化类对应的.hbm.xml:

Accoount.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.sh.entity.Accoount" table="SH_Accoount">
        <id name="id" type="java.lang.Integer">
            <column name="a_id"></column>
            <generator class="native"></generator>
        </id>
        <property name="username" column="a_username" type="java.lang.String"/>
        <property name="balance" column="a_balance" type="java.lang.Integer"/>
    </class>
</hibernate-mapping>

Book.hbm.xml:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.sh.entity.Book" table="SH_Book">
        <id name="id" type="java.lang.Integer">
            <column name="b_id"></column>
            <generator class="native"></generator>
        </id>
        <property name="bookName" column="b_name" type="java.lang.String"/>
        <property name="isbn" column="b_isbn" type="java.lang.String"/>
        <property name="price" column="b_price" type="java.lang.Integer"/>
        <property name="stock" column="b_stock" type="java.lang.Integer"/>
    </class>
</hibernate-mapping>

Spring配置文件:

applicationContext.xml:

<?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" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/aop
          http://www.springframework.org/schema/aop/spring-aop.xsd
         http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">
        
    <!-- 配置数据源 -->
    <!-- 导入资源文件:db.properties -->
    <context:property-placeholder location="classpath:db.properties"/>
    <!-- 配数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${driverclassname}"></property>
        <property name="url" value="${url}"></property>
        <property name="username" value="${user}"></property>
        <!-- 连接池启动时的初始值 -->
        <property name="initialSize" value="1" />
        <!-- 连接池的最大值 -->
        <property name="maxActive" value="500" />
        <!-- 最大空闲值,当经过一个高峰时间后,连接池可以慢慢将已经用不到的连接释放,一直减少到msxIdle为止 -->
        <property name="maxIdle" value="2" />
        <!-- 最小空闲值,当空闲的连接数小于阀值时,连接池就会预申请一些连接,以免洪峰到来时来不及申请 -->
        <property name="minIdle" value="1" />
    </bean>
    <!-- 配置hibernate的sessionFactory实例  通过Spring提供的LocalSessionFactoryBean 进行配置-->
    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <!-- 配置数据源属性 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- 配置hibernate 配置文件位置及名称 -->
        <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
        <!-- 配置hibernate 隐射文件的位置及名称:可以使用通配符 -->
        <property name="mappingLocations">
            <list>
                <value>com/sh/entity/Accoount.hbm.xml</value>
                <value>com/sh/entity/Book.hbm.xml</value>
            </list>
            
        </property>
    </bean>
    
    <!-- 配置Spring的声明式事务 -->
    <!-- 1.配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>
    <!-- 2.配置事务属性 ,需要事务管理器-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="*"/>
        </tx:attributes>
    </tx:advice>
    <!-- 3.配置事务切点,并把切点和事务属性相关联 -->
    <aop:config>
        <aop:pointcut expression="execution(* com.sh.service.*.*(..))" id="txPointcut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>
</beans> 

测试:

public static void main(String[] args) throws SQLException {
        ApplicationContext ac = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        DataSource dataSource = ac.getBean(DataSource.class);
        System.out.println(dataSource.getConnection());
        
    }

输出:自动在数据库中建表并打印出Connection:

jdbc:mysql:///test, UserName=root@localhost, MySQL-AB JDBC Driver

 

posted @ 2016-10-04 21:36  夏文杰  阅读(88)  评论(0)    收藏  举报