String整合hibernate代码测试

在上节生成的表中插入数据:

 

注意:使用myeclipse2014生成的整合项目可能存在问题需要我们自己导入。

 

第一步 我们写dao接口

package com.ssh.spring_hibernate.dao;

 

public
interface BookShopDao {

    //根据书号获取数的单价

    public
int findBookPriceByIsbn(String isbn);

    

    //更新书的库存,使书号对应的库存-1

    public
void updataBookStock(String isbn);

    

    //更新用户的账户余额:使username的balance-price

    public
void
updateUserAccount(String username,int price);

}

写好其实现类

package com.ssh.spring_hibernate.dao;

 

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Repository;

@Repository

public class BookShopDaoImpl implements BookShopDao {

    /**

     * 怎么用hibernate

     * 从SessionFactory中拿到跟当前线程绑定的Session

     */

    

    @Autowired

    private SessionFactory sessionFactory;

    

    public Session getSession(){

        return sessionFactory.getCurrentSession();

    }

    @Override

    public int findBookPriceByIsbn(String isbn) {

        String hql="select b.price from Book b where b.isbn=?";

        Query q=getSession().createQuery(hql).setString(0, isbn);

        return (Integer) q.uniqueResult();

    }

 

    @Override

    public void updataBookStock(String isbn) {

        //验证书的库存是否足够

        String hql2="select b.stock from Book b where b.isbn=?";

        int stock=(Integer) getSession().createQuery(hql2).setString(0, isbn).uniqueResult();

        if (stock==0) {

            System.out.println("库存不足!");

        }

        String hql="update Book b set b.stock=b.stock-1 where b.isbn=?";

        getSession().createQuery(hql).setString(0, isbn).executeUpdate();

    }

 

    @Override

    public void updateUserAccount(String username, int price) {

        //验证余额是否足够

        String hql2="select a.balance from Account a where a.username=?";

        int balance=(Integer) getSession().createQuery(hql2).setString(0, username).uniqueResult();

        System.out.println(balance);

        if (balance<price) {

            System.out.println("余额不足");

        }

        int result=balance-price;

        String hql="update Account a set a.balance=? where a.username=?";

        getSession().createQuery(hql).setInteger(0, result).setString(1, username).executeUpdate();

        System.out.println("余额为"+result);

    }

 

}

 

注意:需要在spring的配置文件中添加自动扫描的路径

<!-- 设置自动扫描的包-->

    <context:component-scan
base-package="com.ssh.spring_hibernate"></context:component-scan>

 

第二步写好service

public
interface BookShopService {

    public
void
purchase(String username,String isbn);

}

 

 

public
interface
Cashier {

    public
void checkout(String username,List<String>isbn);

}

 

其实现类

package com.ssh.spring_hibernate.service;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

 

import com.ssh.spring_hibernate.dao.BookShopDao;

 

@Service

public class BookShopServiceImpl implements BookShopService{

    @Autowired

    private BookShopDao bookShopDao;

    

    @Override

    public void purchase(String username, String isbn) {

        int price =bookShopDao.findBookPriceByIsbn(isbn);

        bookShopDao.updataBookStock(isbn);

        bookShopDao.updateUserAccount(username, price);

    }

 

}

 

package com.ssh.spring_hibernate.service;

 

import java.util.List;

 

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Service;

 

@Service

public
class CashierImpl implements Cashier {

    @Autowired

    private BookShopService bookShopService;

    

    @Override

    public
void checkout(String username, List<String> isbn) {

        for (String is : isbn) {

            bookShopService.purchase(username, is);

        }

        

    }

 

}

 

第三步写我们的测试类

public
class Go {

    

    private ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");

    private BookShopService bookShopService=null;

    {

        bookShopService=ctx.getBean(BookShopService.class);

    }

    

    public
void testDataSource () throws SQLException{

        DataSource d=ctx.getBean(DataSource.class);

        System.out.println(d.getConnection());

    }

    

    public
void testBookShopService(){

        bookShopService.purchase("aa", "1002");

    }

    public
static
void main(String[] args) throws SQLException {

        new Go().testBookShopService();

    }

}

 

 

控制台打印

Hibernate:

select

book0_.PRICE as col_0_0_

from

SH_BOOK book0_

where

book0_.ISBN=?

Hibernate:

select

book0_.STOCK as col_0_0_

from

SH_BOOK book0_

where

book0_.ISBN=?

Hibernate:

update

SH_BOOK

set

STOCK=STOCK-1

where

ISBN=?

Hibernate:

select

account0_.BALANCE as col_0_0_

from

SH_ACCOUNT account0_

where

account0_.USER_NAME=?

Hibernate:

update

SH_ACCOUNT

set

BALANCE=?

where

USER_NAME=?

 

 

Spring Hibernate 事务的流程

  1. 在方法之前
    1. 获取Session
    2. 把Session和当前线程绑定,这样就可以在Dao中使用SessionFactory的getCurrentSession()方法来获取Session了
    3. 开启事务
  2. 若方法正常结束,即没有出现异常,则
    1. 提交事务
    2. 使和当前线程绑定的Session解除绑定
    3. 关闭Session

3若方法出现异常,则

    ① 回滚事务

  1. 使和当前线程绑定的Session解除绑定
  2. 关闭Session

Spring笔记⑤--整合hibernate代码测试的更多相关文章

  1. 【Hibernate学习笔记-3】在Spring下整合Hibernate时, 关于sessionFactory的类型的说明

    摘要 在Spring下整合Hibernate时,关于sessionFactory的配置方式主要有两种,分别为注解配置方式,和xml配置方式,下面将对这两种配置方式进行介绍. 1. sessionFac ...

  2. mybatis与spring的整合(代码实现)

    mybatis与spring的整合(代码实现) 需要jar包: mybatis核心包:依赖包:log4j包:spring croe;beans;tx;aop;aspects;context;expre ...

  3. Spring Boot 整合Hibernate Validator

    Spring Boot 整合Hibernate Validator 依赖 <dependencies> <dependency> <groupId>org.spri ...

  4. spring之整合Hibernate

    spring整合Hibernate整合什么? 1.让IOC容器来管理Hibernate的SessionFactory. 2.让Hibernate使用上spring的声明式事务. 整合步骤: 1.加入H ...

  5. Spring Data-Spring整合Hibernate基于JPA规范

    JPA:由 Sun 公司提供了一对对于持久层操作的标准(接口+文档) Hibernate:是 Gavin King 开发的一套对于持久层操作的自动的 ORM 框架. Hibernate JPA:是在 ...

  6. Java框架:spring框架整合hibernate框架的xml配置(使用注解的方式)

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...

  7. spring框架整合hibernate框架简单操作数据库

    1.配置文件: <?xml version="1.0" encoding="UTF-8"?><beans xmlns="http:/ ...

  8. Spring笔记——配置Hibernate框架事务

    原文:http://www.iteye.com/topic/1123347 Spring配置文件中关于事务配置总是由三个组成部分,DataSource.TransactionManager和代理机制这 ...

  9. 基于注解的Spring MVC整合Hibernate(所需jar包,spring和Hibernate整合配置,springMVC配置,重定向,批量删除)

    1.导入jar watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdG90b3R1enVvcXVhbg==/font/5a6L5L2T/fontsize/400 ...

随机推荐

  1. Java中队列

    定义 队的操作是在两端进行,一端只能进行插入操作(入队),称为队尾,一端只能进行删除操作(出队),称为队尾. 队列的运算规则是FIFO(first in first out). 队列的入队.出队操作分 ...

  2. macOS 开启 VNC 远程桌面和 SSH 服务

    macOS 开启 VNC 远程桌面和 SSH 服务 准备用 macOS 来做为服务器,既然是服务器,那不可缺少的是远程管理,实际上 macOS 自带 VNC 远程桌面和 SSH 服务,只是默认没有开启 ...

  3. centos下安装myrocksdb

    承接上一篇,https://www.cnblogs.com/lunyu/p/10190364.html .编译安装myrocks的整个过程,特别是第2步和第7步,让人冗长难耐.因此编译安装成功后省去这 ...

  4. SAP库龄表

    &---------------------------------------------------------------------* *& Report ZFIR005 *& ...

  5. 径向基(RBF)神经网络python实现

    from numpy import array, append, vstack, transpose, reshape, \ dot, true_divide, mean, exp, sqrt, lo ...

  6. 23-[模块]-subprocess模块

    1.调用系统命令 我们经常需要通过Python去执行一条系统命令或脚本,系统的shell命令是独立于你的python进程之外的,每执行一条命令,就是发起一个新进程,通过python调用系统命令或脚本的 ...

  7. Wannafly挑战赛5 D. 子序列

    D. 子序列 链接 #include<cstdio> #include<algorithm> #include<cstring> #include<iostr ...

  8. .Net Core 管道机制

    开篇先上一张中间件原理图,帮助大家对管道机制形成一个直观的认识 下面我们实现一个简单的管道机制,以此为例深入理解管道机制的原理 1. 首先定义一个委托,该委托接收一个上下文对象,返回值为Task,代码 ...

  9. bzoj 4689: Find the Outlier

    数据不大,枚举哪个式子错了,对剩下的d+2个式子随意选d+1个高斯消元,然后代入剩下的式子检查是否正确,正确就是那一个式子错了 #include<bits/stdc++.h> #defin ...

  10. 使用JDBC连接MySQL数据库

    Java数据库连接(Java DataBase connectivity简称JDBC) 下载JDBC驱动:https://dev.mysql.com/downloads/connector/j/ Wi ...