加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

spring之整合Hibernate

发布时间:2020-12-15 01:13:14 所属栏目:大数据 来源:网络整理
导读:spring整合Hibernate整合什么? 1.让IOC容器来管理Hibernate的SessionFactory。 2.让Hibernate使用上spring的声明式事务。 整合步骤: 1.加入Hibernate。 2.加入spring。 3.整合。 一、加入Hibernate 1.加入相应jar包 加入Hibernate所需的依赖包: 将以上包

spring整合Hibernate整合什么?

1.让IOC容器来管理Hibernate的SessionFactory。

2.让Hibernate使用上spring的声明式事务。

整合步骤:

1.加入Hibernate。

2.加入spring。

3.整合。

一、加入Hibernate

1.加入相应jar包

加入Hibernate所需的依赖包:

将以上包加入到build path。?

加入连接数据库所需的依赖包:

将以上包加入到build path。?

2.添加Hibernate配置文件:hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    session-factory>
        <!-- 配置Hibernate的 基本属性-->
         1.数据源需配置到IOC容器中,此处不再需要配置数据源  2.关联的.hbm.xml也在IOC容器配置SessionFactory实例时再进行配置  3.配置Hibernate的基本属性:方言、SQL显示及格式化,生成数据表的策略以及二级缓存等 property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property="hibernate.show_sql">true="hibernate.format_sql">    
        ="hibernate.hbm2ddl.auto">update 配置二级缓存相关的属性 -->
    >

3.添加实体类以及其hbm配置文件

Account.java

package com.gong.spring.hibernate.entities;

public class Account {

    private Integer id;
     String username;
    private int balance;

    public Integer getId() {
        return id;
    }

    void setId(Integer id) {
        this.id = String getUsername() {
         username;
    }

     setUsername(String username) {
        this.username = getBalance() {
         balance;
    }

    void setBalance( balance) {
        this.balance = balance;
    }

}

Book.java

 Book {

     String bookName;
     String isbn;
     price;
     stock;

     String getBookName() {
         bookName;
    }

     setBookName(String bookName) {
        this.bookName = String getIsbn() {
         isbn;
    }

     setIsbn(String isbn) {
        this.isbn = getPrice() {
         price;
    }

    void setPrice( price) {
        this.price = getStock() {
         stock;
    }

    void setStock( stock) {
        this.stock = stock;
    }

}

Account.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" Generated 2020-1-9 11:56:28 by Hibernate Tools 3.5.0.Final -->
hibernate-mappingclass ="com.gong.spring.hibernate.entities.Account" table="SH_ACCOUNT"id ="id" type="java.lang.Integer">
            column ="ID" />
            generator ="native" />
        id="username"="java.lang.String"="USERNAME" ="balance"="int"="BALANCE" >

Book.hbm.xml

="com.gong.spring.hibernate.entities.Book"="SH_BOOK"="bookName"="BOOKNAME" ="isbn"="ISBN" ="price"="PRICE" ="stock"="STOCK" >

这里需要说明的是table="SH_BOOK"中SH是表的前缀,我们在写hql语句时不用带上,系统会自动识别。

二、加入spring

1.加入相应的jar包

加入spring所需的jar包:

将以上依赖包加入到build path。

2.加入spring配置文件,并进行整合

db.propertites

jdbc.user=root
jdbc.password=123456
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///spring

jdbc.initPoolSize=5
jdbc.maxPoolSize=10

applicationContex.xml

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:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    
     配置自动扫描的包 context:component-scan base-package="com.gong.spring.hibernate"></context:component-scan 配置数据源  导入资源文件 context:property-placeholder location="classpath:db.properties"/>
    
    bean ="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"="user" value="${jdbc.user}"="password"="${jdbc.password}"="driverClass"="${jdbc.driverClass}"="jdbcUrl"="${jdbc.jdbcUrl}">

        ="initialPoolSize"="${jdbc.initPoolSize}"="maxPoolSize"="${jdbc.maxPoolSize}"bean 配置 Hibernate 的 SessionFactory 实例: 通过 Spring 提供的 LocalSessionFactoryBean 进行配置 ="sessionFactory"="org.springframework.orm.hibernate4.LocalSessionFactoryBean" 配置数据源属性  ref="dataSource" 配置 hibernate 配置文件的位置及名称 ="configLocation"="classpath:hibernate.cfg.xml" 使用 hibernateProperties 属相来配置 Hibernate 原生的属性  
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
         配置 hibernate 映射文件的位置及名称,可以使用通配符 ="mappingLocations" 
            value="classpath:com/gong/spring/hibernate/entities/*.hbm.xml">

     配置 Spring 的声明式事务  1. 配置事务管理器 ="transactionManager"="org.springframework.orm.hibernate4.HibernateTransactionManager"="sessionFactory" 2. 配置事务属性,需要事务管理器 tx:advice ="txAdvice" transaction-manager="transactionManager"tx:attributestx:method ="get*" read-only="true"="purchase" propagation="REQUIRES_NEW"="*"tx:advice 3. 配置事务切点,并把切点和事务属性关联起来 aop:configaop:pointcut expression="execution(* com.gong.spring.hibernate.service.*.*(..))" 
            id="txPointcut"aop:advisor advice-ref pointcut-ref/>
    >

beans>

需要注意:假设用的是navicat操作Mysql数据库,对于所连接的数据库,先不要打开,否则不会生成相应的数据表。同时,有两种方式配置hibernate的配置文件,一种是引用外部配置,一种是直接在applicaitonContext.xml文件中进行配置。

最后我们在com.gong.spring.hibernate.test中新建一个SpringHibernateTest.java进行测试:

 com.gong.spring.hibernate.test;

import java.sql.SQLException;
 java.util.Arrays;

 javax.sql.DataSource;

 org.junit.Test;
 org.springframework.context.ApplicationContext;
 org.springframework.context.support.ClassPathXmlApplicationContext;


 SpringHibernateTest {

    private ApplicationContext ctx = null;
    
    {
        ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
    }
    
    @Test
    void testDataSource() throws SQLException {
        DataSource dataSource = ctx.getBean(DataSource.);
        System.out.println(dataSource.getConnection());
    }

}

执行testDataSource方法,在数据库hb中会生成两个实体类的表:

3.进行代码测试

现在的目录结构如下:

使用基于注解的方式来配置bean,需要先在applicationContext.xml中加入:

   <!-->

BookShopDao.java

 com.gong.spring.hibernate.dao;

interface BookShopDao {
    
    //根据书号获取书的单价
     findBookPriceByIsbn(String isbn);
    更新书的库存,使书号对应的库存-1
     updateBookStock(String isbn);
    更新账户余额:使username的balance-price
    void updateUserAccount(String username, price);
}

BookShopDaoImpl.java

 com.gong.spring.hibernate.dao.impl;

 org.hibernate.Query;
 org.hibernate.Session;
 org.hibernate.SessionFactory;
 org.springframework.beans.factory.annotation.Autowired;
 org.springframework.stereotype.Repository;

 com.gong.spring.hibernate.dao.BookShopDao;
 com.gong.spring.hibernate.exceptions.BookStockException;
 com.gong.spring.hibernate.exceptions.UserAccountException;

@Repository
class BookShopDaoImpl implements BookShopDao {
    @Autowired
     SessionFactory sessionFactory;
    
    获取当前绑定的session
     Session getSession() {
         sessionFactory.getCurrentSession();
    }
    @Override
     findBookPriceByIsbn(String isbn) {
        String hql = "SELECT b.price FROM Book b WHERE b.isbn = ?";
        Query query = getSession().createQuery(hql).setString(0,isbn);
         (Integer) query.uniqueResult();
    }

    @Override
     updateBookStock(String isbn) {
        验证书的库存是否充足
        String hql2 = "SELECT b.stock FROM Book b WHERE b.isbn = ?";
        检查书的库存是否足够,如果不够,就抛出异常
        int stock = (int) getSession().createQuery(hql2).setString(0if(stock == 0){
            throw new BookStockException("库存不足!");
        }    
        String hql = "UPDATE Book b set b.stock = b.stock-1 WHERE b.isbn = ?";
        getSession().createQuery(hql).setString(0 price) {
        String hql2 = "SELECT a.balance FROM Account a WHERE a.username = ?"int balance = (if(balance < price){
            new UserAccountException("余额不足!");
        }
        
        String hql = "UPDATE Account a SET a.balance = a.balance - ? WHERE a.username = ?";
        getSession().createQuery(hql).setInteger(0,price).setString(1会将数据表当作对象来看,因此数据表的首字母要大写

BookShopException.java和UserAccountException.java是我们自己定义的异常。

BookShopException.java

 com.gong.spring.hibernate.exceptions;

class BookStockException extends RuntimeException{

    /**
     * 
     */
    static final long serialVersionUID = 1L;

     BookStockException() {
        super();
         TODO Auto-generated constructor stub
    }

     BookStockException(String message,Throwable cause,boolean enableSuppression,1)">boolean writableStackTrace) {
        (message,cause,enableSuppression,writableStackTrace);
         BookStockException(String message) {
        (message);
         BookStockException(Throwable cause) {
        (cause);
            }

    
}

UserAccountException.java

class UserAccountException  UserAccountException() {
         UserAccountException(String message,1)"> UserAccountException(String message) {
         UserAccountException(Throwable cause) {
            }

    
    
}

其实就是为异常取了个名字,然后改为自己想要输出的错误信息。

BookShopService.java(用于测试买单本书时候的事务)

 com.gong.spring.hibernate.service;

 BookShopService {
    
     purchase(String username,String isbn);
    
}

Cashier.java(用于测试买多本书时候的事务)

 java.util.List;

 Cashier {

    void checkout(String username,List<String> isbns);
    
}

BookShopServiceImpl.java

 com.gong.spring.hibernate.service.impl;

 org.springframework.stereotype.Service;

 com.gong.spring.hibernate.dao.BookShopDao;

 com.gong.spring.hibernate.service.BookShopService;

@Service
class BookShopServiceImpl  BookShopService {

    @Autowired
     BookShopDao bookShopDao;

    1. 获取书的单价
        int price = bookShopDao.findBookPriceByIsbn(isbn);
        
        2. 更新库存
        bookShopDao.updateBookStock(isbn);
        
        3. 更新余额
        bookShopDao.updateUserAccount(username,price);
    }

}

CashierImpl.java

 org.springframework.stereotype.Service;
 org.springframework.transaction.annotation.Propagation;
 org.springframework.transaction.annotation.Transactional;

 com.gong.spring.hibernate.service.BookShopService;
 com.gong.spring.hibernate.service.Cashier;

@Service
class CashierImpl  Cashier {
    
    @Autowired
     BookShopService bookShopService;

    @Override
     isbns) {
        for(String isbn: isbns){
            bookShopService.purchase(username,isbn);
        }
    }

}

最后,我们在SpringHibernateTest.java中进行测试:

 org.springframework.context.support.ClassPathXmlApplicationContext;

 com.gong.spring.hibernate.service.Cashier;


;
    private BookShopService bookShopService = private Cashier cashier = );
        bookShopService = ctx.getBean(BookShopService.);
        cashier = ctx.getBean(Cashier. testCashier(){
        cashier.checkout("AA",Arrays.asList("1001","1002"));
    }
    
    @Test
     testBookShopService(){
        bookShopService.purchase("AA","1001");
        System.out.println(dataSource.getConnection());
    }

}

首先我们往数据库中添加如下数据:

先测试?testBookShopService方法,结果如下:成功购买了一本java书。

再执行一次该方法:出现异常,余额不足,结果为:

说明我们的spring+hibernate事务是配置成功。

接下来我们测试事务的传播方式,即testCashier方法,首先我们将数据设置为:

第一次执行后的结果:成功买到两本书:

再执行一次:

只买了第一本书,第二本余额不足,因为我们在配置时指定了<tx:method name="purchase" propagation="REQUIRES_NEW"/>。如果设置?propagation="REQUIRD,那么就会一本都买不成功。具体原因可以参考之前所写的博客。

4.总结

至此,spring整合hibernate就基本完成了。

最后补充一些:

Spring Hibernate事务的流程:

(1)在方法执行之前获取session;

(2)把session和当前线程绑定,这样就可以在Dao中使用SessionFactory的getCurrentSession()来获取session;

(3)开启事务;

(4)若方法正常结束,即没有出现异常,则先提交事务,然后使当前线程绑定的session解除绑定,最后关闭session;

(5)若方法出现异常,则先回滚事务,然后使当前线程绑定的session解除绑定,最后关闭session;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读