zoukankan      html  css  js  c++  java
  • Spring学习整合hibernate(四)

    用到的Jar包

    antlr-2.7.7.jar
    c3p0-0.9.1.2.jar
    com.springsource.net.sf.cglib-2.2.0.jar
    com.springsource.org.aopalliance-1.0.0.jar
    com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
    commons-logging-1.1.3.jar
    dom4j-1.6.1.jar
    hibernate-commons-annotations-4.0.2.Final.jar
    hibernate-core-4.2.4.Final.jar
    hibernate-jpa-2.0-api-1.0.1.Final.jar
    javassist-3.15.0-GA.jar
    jboss-logging-3.1.0.GA.jar
    jboss-transaction-api_1.1_spec-1.0.1.Final.jar
    mysql-connector-java-5.1.7-bin.jar
    spring-aop-4.0.0.RELEASE.jar
    spring-aspects-4.0.0.RELEASE.jar
    spring-beans-4.0.0.RELEASE.jar
    spring-context-4.0.0.RELEASE.jar
    spring-core-4.0.0.RELEASE.jar
    spring-expression-4.0.0.RELEASE.jar
    spring-jdbc-4.0.0.RELEASE.jar
    spring-orm-4.0.0.RELEASE.jar
    spring-tx-4.0.0.RELEASE.jar
    spring-web-4.0.0.RELEASE.jar
    spring-webmvc-4.0.0.RELEASE.jar

    Spring整合hibernate思路

      先配置hibernate文件,之后配置Spring文件

    hibernate配置文件

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <!DOCTYPE hibernate-configuration PUBLIC
     3         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
     4         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
     5 <hibernate-configuration>
     6     <session-factory>
     7     
     8         <!-- 配置 hibernate 的基本属性 -->
     9         <!-- 1. 数据源需配置到 IOC 容器中, 所以在此处不再需要配置数据源 -->
    10         <!-- 2. 关联的 .hbm.xml 也在 IOC 容器配置 SessionFactory 实例时在进行配置 -->
    11         <!-- 3. 配置 hibernate 的基本属性: 方言, SQL 显示及格式化, 生成数据表的策略以及二级缓存等. -->
    12         <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
    13 
    14         <property name="hibernate.show_sql">true</property>
    15         <property name="hibernate.format_sql">true</property>
    16         <!-- 自动生成数据表 -->
    17         <property name="hibernate.hbm2ddl.auto">update</property>
    18         
    19         <!-- 配置 hibernate 二级缓存相关的属性. -->
    20                 
    21     </session-factory>
    22 </hibernate-configuration>

    spring配置文件

     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:tx="http://www.springframework.org/schema/tx"
     6     xmlns:aop="http://www.springframework.org/schema/aop"
     7     xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
     8         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
     9         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    10         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
    11 
    12     <!-- 配置自动扫描的包 -->
    13     <context:component-scan base-package="com.spring.hibernate"></context:component-scan>
    14     <!-- 导入资源文件 -->
    15     <context:property-placeholder location="classpath:db.properties" />
    16 
    17     <!-- 配置C3P0数据源 -->
    18     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    19         <property name="user" value="${jdbc.user}"></property>
    20         <property name="password" value="${jdbc.password}"></property>
    21         <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
    22         <property name="driverClass" value="${jdbc.driverClass}"></property>
    23 
    24         <property name="initialPoolSize" value="${jdbc.initPoorSize}"></property>
    25         <property name="maxPoolSize" value="${jdbc.maxPoorSize}"></property>
    26     </bean>
    27 
    28     <!-- 配置hibernate的SessionFactory 实例:通过LocalSessionFactoryBean进行配置 -->    
    29     <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    30         <!-- 配置数据源属性 -->
    31         <property name="dataSource" ref="dataSource"></property>
    32         <!-- 配置hibernate的配置文件的位置以及名称 -->
    33         <property name="configLocations" value="classpath:hibernate.cfg.xml"></property>
    34         <!-- 配置hibernate映射文件的位置及名称,可以使用通配符 -->
    35         <property name="mappingLocations" value="classpath:com/spring/hibernate/entities/*.hbm.xml"></property>
    36     </bean>
    37     
    38     <!-- 配饰Spring的声明式事务 -->
    39     <!-- 1.配置事务管理器 -->
    40     <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    41         <property name="sessionFactory" ref="sessionFactory"></property>
    42     </bean>
    43     
    44     <!-- 2.配置事务属性 需要事务管理器-->
    45     <tx:advice id="txAdvice" transaction-manager="transactionManager">
    46         <tx:attributes>
    47             <tx:method name="get*" read-only="true"></tx:method>
    48             <tx:method name="purchase" propagation="REQUIRED"></tx:method>
    49             <tx:method name="*"></tx:method>
    50         </tx:attributes>
    51     </tx:advice>
    52     
    53     <!-- 3.配置事务切点,并把切点和事务关联起来 -->
    54     <aop:config>
    55         <aop:pointcut expression="execution(* com.spring.hibernate.service.*.*(..))" 
    56         id="txPointcut"/>
    57         <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    58     </aop:config>
    59     
    60 </beans>

    dao层实现类

     1 package com.spring.hibernate.daoImpl;
     2 
     3 import org.hibernate.Query;
     4 import org.hibernate.Session;
     5 import org.hibernate.SessionFactory;
     6 import org.springframework.beans.factory.annotation.Autowired;
     7 import org.springframework.stereotype.Repository;
     8 
     9 import com.spring.hibernate.dao.BookShopDao;
    10 import com.spring.hibernate.exception.BookStockException;
    11 import com.spring.hibernate.exception.UserAccountException;
    12 
    13 @Repository
    14 public class BookShopDaoImpl implements BookShopDao {
    15 
    16     @Autowired
    17     private SessionFactory sessionFactory;
    18     
    19 //    获取和当前线程绑定的线程
    20     private Session getSession(){
    21         return sessionFactory.getCurrentSession();
    22     }
    23     
    24     @Override
    25     public int findBookPriceByIsbn(String isbn) {
    26         String hql = "select b.price from Book b where b.isbn = ?";
    27         Query query = getSession().createQuery(hql).setString(0, isbn);
    28         return (Integer) query.uniqueResult();
    29     }
    30 
    31     @Override
    32     public void updateBookStock(String isbn) {
    33         String hql2 = "select b.stock from Book b where b.isbn =?";
    34         Integer stock = (Integer) getSession().createQuery(hql2).setString(0, isbn).uniqueResult();
    35         if(stock ==0){
    36             throw new BookStockException("库存不足");
    37         }
    38         String hql = "update Book b set b.stock=b.stock -1 where b.isbn =?";
    39         getSession().createQuery(hql).setString(0, isbn).executeUpdate();
    40     }
    41 
    42     @Override
    43     public void updateUserAccount(String username, int price) {
    44 //        验证余额是否足够
    45         String hql2 = "select a.balance from Account a where a.username = ?";
    46         Integer balance = (Integer) getSession().createQuery(hql2).setString(0, username).uniqueResult();
    47         if(balance < price){
    48             throw new UserAccountException("余额不足");
    49         }
    50         String hql = "UPDATE Account a SET a.balance = a.balance - ? where a.username = ? ";
    51         getSession().createQuery(hql).setInteger(0, price).setString(1, username).executeUpdate();
    52     }
    53 
    54 }

    service实现类

     1 package com.spring.hibernate.service.Impl;
     2 
     3 import java.util.List;
     4 
     5 import org.springframework.beans.factory.annotation.Autowired;
     6 import org.springframework.stereotype.Service;
     7 
     8 import com.spring.hibernate.service.BookShopService;
     9 import com.spring.hibernate.service.CashierService;
    10 
    11 @Service("cashierService")
    12 public class CashierServiceImpl implements CashierService {
    13 
    14     @Autowired
    15     private BookShopService bookShopService;
    16     
    17     /**
    18      * Spring hibernate 事务的流程
    19      * 1.方法开始之前
    20      * a.获取session
    21      * b.把session和当前线程绑定,这样就可以在Dao中使用SessionFactory的getSession()方法来获取session了
    22      * c.开启事务
    23      * 
    24      * 2.若方法正常提交结束,没有出现异常
    25      * a.提交事务
    26      * b.使和当前绑定的session解除绑定
    27      * c.关闭session
    28      * 
    29      * 3.若方法出现异常
    30      * a.回滚事务
    31      * b.使和当前绑定的session解除绑定
    32      * c.关闭session
    33      */
    34     
    35     @Override
    36     public void checkout(String username, List<String> ibsns) {
    37         for(String isbn:ibsns){
    38             bookShopService.purchase(username, isbn);
    39         }
    40     }
    41 
    42 }

    实体类对应生成hbm.xml文件

     1 <?xml version="1.0"?>
     2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
     4 
     5 <hibernate-mapping>
     6     <class name="com.spring.hibernate.entities.Account" table="SH_ACCOUNT">
     7         
     8         <id name="id" type="java.lang.Integer">
     9             <column name="ID" />
    10             <generator class="native" />
    11         </id>
    12         
    13         <property name="username" type="java.lang.String">
    14             <column name="USERNAME" />
    15         </property>
    16         
    17         <property name="balance" type="int">
    18             <column name="BALANCE" />
    19         </property>
    20         
    21     </class>
    22 </hibernate-mapping>
     1 <?xml version="1.0"?>
     2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
     3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
     4 
     5 <hibernate-mapping>
     6     <class name="com.spring.hibernate.entities.Book" table="SH_BOOK">
     7     
     8         <id name="id" type="java.lang.Integer">
     9             <column name="ID" />
    10             <generator class="native" />
    11         </id>
    12         
    13         <property name="bookName" type="java.lang.String">
    14             <column name="BOOK_NAME" />
    15         </property>
    16         
    17         <property name="isbn" type="java.lang.String">
    18             <column name="ISBN" />
    19         </property>
    20         
    21         <property name="price" type="int">
    22             <column name="PRICE" />
    23         </property>
    24         
    25         <property name="stock" type="int">
    26             <column name="STOCK" />
    27         </property>
    28         
    29     </class>
    30 </hibernate-mapping>
  • 相关阅读:
    KMeans算法分析以及实现
    决策树(ID3,C4.5,CART)原理以及实现
    [推荐系统读书笔记]利用用户标签数据
    [推荐系统读书笔记]推荐系统冷启动问题
    [推荐系统]利用用户行为数据
    [推荐系统读书笔记]好的推荐系统
    Docker Hub国内镜像加速
    ubuntu下cannot connect to X server :1
    vscode编写C++设置左花括号不换行
    SLAM十四讲中Sophus库安装
  • 原文地址:https://www.cnblogs.com/duyunchao-2261/p/7505941.html
Copyright © 2011-2022 走看看