天天看点

Spring 整合 Hibernate

         PS:前段时间一直都在学校,要么上课,要么做学期最后的课程设计,一直无暇整理所学。前些天刚来公司实习,感觉好像对于三大框架的应用并没有很多,只有Spring,也是为了对过去的总结,也是为了怕自己后来再用的时候又要各处找资料。及时的把框架整合进行整理,迎接新的工作~~

1.Spring 整合 Hibernate 整合什么?   1)有 IOC 容器来管理 Hibernate 的 SessionFactory;   2)让 Hibernate 使用 Spring 的声明式事务。 [事务:一系列的动作,它们被当做一个单独的工作单元,这些动作要么全部完成,要么全部不起作用]

2.整合步骤   1)加入 hibernate : 编写持久化类对应的 .hbm.xml   2)加入 Spring      1>加入jar包      2>加入Spring的配置文件,即整合的过程   [命名空间]

Spring 整合 Hibernate

 3)整合(spring2.0)      1.配置数据源

Spring 整合 Hibernate

  <bean id="dataSource"          class="org.springframework.jdbc.datasource.DriverManagerDataSource">      <property name="driverClassName"           value="oracle.jdbc.driver.OracleDriver">      </property>      <property name="url"            value="jdbc:oracle:thin:@localhost:1521:inspur">      </property>      <property name="username" value="scott"></property>      <property name="password" value="tiger"></property>    </bean>  2.配置 Hibernate 的 SessionFactory 实例

Spring 整合 Hibernate

(通过 Spring 提供的 LocalSessionFactoryBean 进行配置)     <bean id="sessionFactory"           class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">       <!-- 配置数据源属性 -->       <property name="dataSource" ref="dataSource"></property>       <!-- 用来列出全部映射文件(位置及名称) -->       <property name="mappingResources">           <!-- *.hbm.xml -->           <list>             <value>com/inspur/entity/Account.hbm.xml</value>             <value>com/inspur/entity/Book.hbm.xml</value>           </list>       </property>       <!-- 定义Hibernate的SessionFactory属性 -->       <property name="hibernateProperties">           <props>               <prop key="hibernate.dialect">                 org.hibernate.dialect.Oracle10gDialect           </prop>           <prop key="hibernate.hbm2ddl.auto">update</prop>           <prop key="hibernate.show_sql">true</prop>           </props>       </property>     </bean>      3.配置Spring的声明式事务

Spring 整合 Hibernate

 <!-- 配置Hibernate的局部事务管理器 -->      <bean id="transactionManager"            class="org.springframework.orm.hibernate3.HibernateTransactionManager">          <property name="sessionFactory" ref="sessionFactory"></property>      </bean>      <!-- 配置事务的通知(需要引入 tx 命名空间) -->      <tx:advice id="transaction"          transaction-manager="transactionManager">           <!-- 为每类方法配置各自的事务 -->           <tx:attributes>               <tx:method name="get*" read-only="true" />               <tx:method name="*" propagation="REQUIRED"                   isolation="READ_COMMITTED" />          </tx:attributes>     </tx:advice>     <!-- 配置事务切点,并把切点和事务属性(通知)关联起来(需要引入 aop 命名空间)service实现类做切点 -->     <aop:config>          <aop:pointcut id="txPointcut"               expression="execution(* com.inspur.service.impl.*.*(..))" />          <aop:advisor advice-ref="transaction" pointcut-ref="txPointcut" />     </aop:config> 以上是配置文件,虽然大多时候可以copy , paste 来完成,但是自己还是经常手写来配置,加深印象。下面通过代码对比较重要的地方进行解释。[对 hibernateTemplate 以及 SessionFactory 的区别进行解释]

package com.inspur.dao.impl;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import com.inspur.dao.BookDao;
public class BookDaoImpl implements BookDao {
 // Hibernate 模板类 但不推荐如此使用
 /**
  * 原因:HibernateTemplate 是 Spring 中的类,不支持 Spring4 因为这样会导致 Dao 和 Spring 的 API
  * 进行耦合,导致可移植性变差 当 Hibernate 和 Spring 整合,可以如此使用。只是可移植性变差
  */
 /*
  * private HibernateTemplate hibernateTemplate;
  *
  * public HibernateTemplate getHibernateTemplate() { return
  * hibernateTemplate; }
  *
  * public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
  * this.hibernateTemplate = hibernateTemplate; }
  */
 // SessionFactory Hibernate 原生 API
 public SessionFactory sessionFactory;
 // 获取跟当前线程绑定的Session*****
 public Session getSession() {
  return sessionFactory.getCurrentSession();
 }
 // SessionFactory 的 get、set 方法
 public SessionFactory getSessionFactory() {
  return sessionFactory;
 }
 public void setSessionFactory(SessionFactory sessionFactory) {
  this.sessionFactory = sessionFactory;
 }
 /**
  * 根据书号获取书的单价
  */
 public int findBookPriceByIsbn(String isbn) {
  String hql = "select b.price from Book as b where b.isbn = ?";
  Query query = getSession().createQuery(hql).setString(0, isbn);
  return (Integer) query.uniqueResult();
 }
 /**
  * 更新书的库存,使书号对应的库存 -1
  */
 public void updateBookStock(String isbn) {
  // 验证书的库存是否充足
  String hql2 = "select b.stock from Book as b where b.isbn = ?";
  int stock = (Integer) getSession().createQuery(hql2).setString(0, isbn)
    .uniqueResult();
  if (stock == 0) {
   System.out.println("库存不足!");
  }
  String hql = "update Book as b set b.stock = b.stock - 1 where b.isbn = ?";
  getSession().createQuery(hql).setString(0, isbn).executeUpdate();
 }
 /**
  * 更新用户的账户余额:使username的balance - price
  */
 public void updateUserAccount(String username, int price) {
  // 验证余额是否足够
  String hql2 = "select a.balance from Account as a where a.username = ?";
  int balance = (Integer) getSession().createQuery(hql2).setInteger(0,
    price).uniqueResult();
  if (balance < price) {
   System.out.println("余额不足!");
  }
  String hql = "update Account as a set a.balance = a.balance - ? where a.username = ?";
  getSession().createQuery(hql).setInteger(0, price).setString(1,
    username).executeUpdate();
 }
}