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. SQL进阶语法的多表操作

    AS别名 多张表联合操作,如果表多,字段名长,不方便阅读.这里我们可以使用  as  关键字来对字段名设置别名. as也可以省略,看个人喜好,在这里我还是支持把 as 写上,这样我们在面对复杂的SQL ...

  2. SAP查找用户的登录记录

    1.可以使用USR02中有个上次登陆日期和登陆时间. 2.用SE38跑下RSUSR200,输入用户名即可查询上次登陆日期 3.SU10可以查到

  3. cnn 滤波

    http://blog.csdn.net/zouxy09/article/details/49080029

  4. 2018年美国大学生数学建模竞赛(MCM/ICM) C题解题思路

    整个赛题是一道大数据的深层挖掘与分析赛题,数据在这是很重要的组成因 素,因此大家首先应该把题目所给的数据搞清楚搞明白.赛题的关键是能源生产 和使用的合理安排,针对第一部分,主要解决能源的配置与评价问题 ...

  5. gitlab 配置 ssh key

    打开本地git bash,使用如下命令生成ssh公钥和私钥对 ssh-keygen -t rsa -C 'xxx@xxx.com' 然后一路回车(-C 参数是你的邮箱地址) 然后打开~/.ssh/id ...

  6. c语言数字图像处理(八):噪声模型及均值滤波器

    图像退化/复原过程模型 高斯噪声 PDF(概率密度函数) 生成高斯随机数序列 算法可参考<http://www.doc.ic.ac.uk/~wl/papers/07/csur07dt.pdf&g ...

  7. vue里extend、mixins、extends的区别

    1.extend Vue.extend使用基础 Vue 构造器,创建一个"子类".参数是一个包含组件选项的对象. // Vue.extend // 创建构造器 var Profil ...

  8. 六度空间(MOOC)

    六度空间: “六度空间”理论又称作“六度分隔(Six Degrees of Separation)”理论.这个理论可以通俗地阐述为:“你和任何一个陌生人之间所间隔的人不会超过六个,也就是说,最多通过五 ...

  9. FFMS2 官方说明译文 [原创]

    原文:https://github.com/FFMS/ffms2 译文:http://www.cnblogs.com/popapa/p/ffms2.html 采集日期:2018-3-18 FFmpeg ...

  10. RAID中条带的概念

    raid把数据分成条带,一个条带横跨所有数据磁盘,每个磁盘上存储条带的一部分,称为sagment,也称为条带深度.一个条带包含的扇区或块的个数,称为条带长度. raid向操作系统提供的是卷,是连续的扇 ...