Spring整合Hibernate。。。。
环境搭建,在eclipse中导入spring和hibernate框架的插件,和导入所有使用到的架包
首先,hibernate的创建:
建立两个封装类,其中封装了数据库中表的属性,这儿只写属性,getter和setter方法就不写了
类:Account中的属性
private Integer id;
private String username;
private int balance;
类:Book中的属性
private Integer id;
private String bookName;
private String isbn;//书号码
private int price;
private int stock;//书的库存数量
在该包下建立Hibernate XML Mapping file(hbm.xml)的映射文件,其是自动生成的,直接点击下一步,下一步。。。,需要说明的是,其映射文件将封装类中的属性和数据库中表的属性相关联
<hibernate-mapping>
<class name="com.atguigu.springhibernate.entities.Account" table="ACCOUNTS">
//name,为,类中属性名,type为属性的类型,<column name..>为数据库中表的属性,下边是主键的生成方式
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="native" />
</id>
<property name="username" type="java.lang.String">
<column name="USERNAME" />
</property>
<property name="balance" type="int">
<column name="BALANCE" />
</property>
</class>
</hibernate-mapping>
<hibernate-mapping>
<class name="com.atguigu.springhibernate.entities.Book" table="BOOK">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="native" />
</id>
<property name="bookName" type="java.lang.String">
<column name="BOOK_NAME" />
</property>
<property name="isbn" type="java.lang.String">
<column name="ISBN" />
</property>
<property name="price" type="int">
<column name="PRICE" />
</property>
<property name="stock" type="int">
<column name="STOCK" />
</property>
</class>
</hibernate-mapping>
在src目录下建立 Hibernate Configuration File(cfg)为 hibernate.cfg.xml,其是hibernate和配置文件
<hibernate-configuration>
<session-factory> <!-- hibernate的配置文件 -->
<!-- 1. 数据源需配置到 IOC 容器中, 所以在此处不再需要配置数据源 -->
<!-- 2. 关联的 .hbm.xml 也在 IOC 容器配置 SessionFactory 实例时在进行配置 -->
<!-- 3. 配置 hibernate 的基本属性: 方言, SQL 显示及格式化, 生成数据表的策略以及二级缓存等. -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <property name="hibernate.show_sql">true</property> <property name="hibernate.format_sql">true</property> <property name="hibernate.hbm2ddl.auto">update</property> <!-- 配置hibernate二级缓存的配置 --> </session-factory>
</hibernate-configuration>
--------------------------------------------------------------------------------
然后spring框架整合hibernate。。。
建立一个接口
package com.atguigu.springhibernate.dao;
import java.util.List;
public interface BookShopDao {
//根据书号获取书的单价
public int findBookPriceByIsbn(String isbn);
//更新数的库存. 使书号对应的库存 - 1
public void updateBookStork(String isbn);
//更新用户的账户余额: 使 username 的 balance - price
public void updateUserAccount(String username,int price);
//购买批量的书籍,更新用户的余额
public int updateBatch(String username,List<String> isbns);
}
建立一个类,实现上边的接口,方法是。。。,用的是hql语句,其是面向对象的,表名为其对应的类名,即写hql语句时表名首字母大写。。。
package com.atguigu.springhibernate.dao.impl; import java.util.List; import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository; import com.atguigu.springhibernate.dao.BookShopDao;
import com.atguigu.springhibernate.exceptions.BookStockException;
import com.atguigu.springhibernate.exceptions.UserAccountException; @Repository
public class BookShopDaoImpl implements BookShopDao{ @Autowired
private SessionFactory sessionFactory; //获取和当前线程绑定的 Session.
private Session getSession(){
return sessionFactory.getCurrentSession();
} /*
* hql是面向对象的,其表名为该表所映射的类名,即表名首字母大写
* */
//根据书号获取书的单价
public int findBookPriceByIsbn(String isbn) {
String hql="SELECT b.price FROM Book b WHERE b.isbn = ?";
Query query=getSession().createQuery(hql).setString(0, isbn);
return (Integer) query.uniqueResult();
} //更新数的库存. 使书号对应的库存 - 1
public void updateBookStork(String isbn) {
//验证书的库存是否充足.
String hql2="select b.stock from Book b where isbn=?";
int stock= (Integer) getSession().createQuery(hql2).setString(0, isbn).uniqueResult();
if(stock==0){
System.out.println("该书的库存不足!!!");
throw new BookStockException("该书的库存不足!!!");
} String hql="update Book 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 a where a.username=?";
int balance=(Integer) getSession().createQuery(hql2).setString(0, username).uniqueResult();
if(balance<price){
//System.out.println("账户的余额不足了!!!");
throw new UserAccountException("账户余额不足了!!!!");
} String hql="update Account a set a.balance=a.balance-? where username=?";
getSession().createQuery(hql).setInteger(0, price).setString(1, username).executeUpdate();
} public int updateBatch(String username, List<String> isbns) {
//批量购买,首先验证余额是否足够 //购买的所有书籍的总钱数
int money=0;
String hql2="select b.price from Book b where b.isbn=?";
for(String isbn:isbns){
money+=(Integer) getSession().createQuery(hql2).setString(0, isbn).uniqueResult();
} //用户的账户余额
String hql="select a.balance from Account a where a.username=?";
int balance=(Integer) getSession().createQuery(hql).setString(0, username).uniqueResult(); if(money>balance){
throw new UserAccountException("余额不足,不能购买全部书籍");
}
return 0;
} }
在建立两个接口,
package com.atguigu.springhibernate.service;
import java.util.List;
public interface Cashier {
public void checkout(String username,List<String> isbns);
}
package com.atguigu.springhibernate.service;
public interface BookShopService {
public void purchase(String username,String isbn);
}
建立两个类分别实现上边的两个接口。。。
package com.atguigu.springhibernate.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.atguigu.springhibernate.dao.BookShopDao;
import com.atguigu.springhibernate.service.Cashier; @Service
public class CashierImpl implements Cashier { @Autowired
private BookShopDao bookShopDao;
//批量购买书籍
public void checkout(String username, List<String> isbns) {
//购买批量的书籍
bookShopDao.updateBatch(username, isbns); } }
package com.atguigu.springhibernate.service.impl; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.atguigu.springhibernate.dao.BookShopDao;
import com.atguigu.springhibernate.service.BookShopService; @Service
public class BookShopServiceImpl implements BookShopService { @Autowired
private BookShopDao bookShopDao; /**
* Spring hibernate 事务的流程
* 1. 在方法开始之前
* ①. 获取 Session
* ②. 把 Session 和当前线程绑定, 这样就可以在 Dao 中使用 SessionFactory 的
* getCurrentSession() 方法来获取 Session 了
* ③. 开启事务
*
* 2. 若方法正常结束, 即没有出现异常, 则
* ①. 提交事务
* ②. 使和当前线程绑定的 Session 解除绑定
* ③. 关闭 Session
*
* 3. 若方法出现异常, 则:
* ①. 回滚事务
* ②. 使和当前线程绑定的 Session 解除绑定
* ③. 关闭 Session
*/
public void purchase(String username, String isbn) {
//由书的编号,的出书的价格
int price = bookShopDao.findBookPriceByIsbn(isbn); //由书的编号,更新书的库存
bookShopDao.updateBookStork(isbn); //更新该用户的账户余额
bookShopDao.updateUserAccount(username, price);
} }
在src目录下建立jdbc.properties文件:是连接数据库的基本属性和值
jdbc.user=root
jdbc.password=lxn123
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///spring_hibernate jdbc.initPoolSize=5
jdbc.maxPoolSize=10
在src下建立Spring Bean Configuration File的xml文件:applicationContext.xml,是spring的bean的配置文件和整合hibernate的文件
<!-- 配置自动扫描的包,及其子包,基于注解的bean配置 -->
<context:component-scan base-package="com.atguigu.springhibernate"></context:component-scan> <!-- 配置数据源 -->
<!-- 导入资源文件 ,根目录(src)下的文件-->
<context:property-placeholder location="classpath:jdbc.properties"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<property name="driverClass" value="${jdbc.driverClass}"></property>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
</bean> <!-- 配置 Hibernate 的 SessionFactory 实例: 通过 Spring 提供的 LocalSessionFactoryBean 进行配置 -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- 配置数据源属性 -->
<property name="dataSource" ref="dataSource"></property> <!-- 配置 hibernate 配置文件的位置及名称 -->
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property> <!-- 配置 hibernate 映射文件的位置及名称, 可以使用通配符 -->
<property name="mappingLocations"
value="classpath:com/atguigu/springhibernate/entities/*.hbm.xml"></property>
</bean> <!-- 配置 Spring 的声明事务 -->
<!-- 1. 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean> <!-- 2. 配置事务属性, 需要事务管理器 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="get*" read-only="true"/> <!-- 设置事物的传播行为,设置为新事物 -->
<tx:method name="purchase" propagation="REQUIRES_NEW"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice> <!-- 3. 配置事务切点, 并把切点和事务属性关联起来 -->
<aop:config>
<aop:pointcut expression="execution(* com.atguigu.springhibernate.service.*.*(..))"
id="txPointcut"/>
<!-- 把切点和事物属性关联起来 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
</aop:config>
建立一个测试类,对上面的方法进行测试;
package com.atguigu.springhibernate.test; import java.sql.SQLException;
import java.util.Arrays; import javax.sql.DataSource; import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.atguigu.springhibernate.service.BookShopService;
import com.atguigu.springhibernate.service.Cashier; public class SpringHibernateTest { private static ApplicationContext ctx=null;
private static BookShopService bookShopService=null;
private static Cashier cashier=null; {
ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
bookShopService=ctx.getBean(BookShopService.class);
cashier=ctx.getBean(Cashier.class);
} @Test
public void testCashier(){
cashier.checkout("AAA", Arrays.asList("1001","1002"));
} @Test
public void testBookShopService() {
bookShopService.purchase("AAA", "1001"); } //测试数据库连接池是否连接成功
public void jdbcConnection() throws SQLException{
DataSource dataSource=(DataSource) ctx.getBean("dataSource");
System.out.println(dataSource.getConnection());
} }
--------------------------------------------------------------------------------
在包com.atguigu.springhibernate.exceptions下建立两个异常类:其继承于RuntimeException,便于前面对异常的处理时,直接调用;
package com.atguigu.springhibernate.exceptions;
public class UserAccountException extends RuntimeException{
private static final long serialVersionUID = 1L;
public UserAccountException() {
super();
}
public UserAccountException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public UserAccountException(String message, Throwable cause) {
super(message, cause);
}
public UserAccountException(String message) {
super(message);
}
public UserAccountException(Throwable cause) {
super(cause);
}
}
package com.atguigu.springhibernate.exceptions;
public class BookStockException extends RuntimeException{
private static final long serialVersionUID = 1L;
public BookStockException() {
super();
}
public BookStockException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public BookStockException(String message, Throwable cause) {
super(message, cause);
}
public BookStockException(String message) {
super(message);
}
public BookStockException(Throwable cause) {
super(cause);
}
}
Spring整合Hibernate。。。。的更多相关文章
- 【Java EE 学习 53】【Spring学习第五天】【Spring整合Hibernate】【Spring整合Hibernate、Struts2】【问题:整合hibernate之后事务不能回滚】
一.Spring整合Hibernate 1.如果一个DAO 类继承了HibernateDaoSupport,只需要在spring配置文件中注入SessionFactory就可以了:如果一个DAO类没有 ...
- spring整合hibernate的详细步骤
Spring整合hibernate需要整合些什么? 由IOC容器来生成hibernate的sessionFactory. 让hibernate使用spring的声明式事务 整合步骤: 加入hibern ...
- spring整合hibernate
spring整合hibernate包括三部分:hibernate的配置.hibernate核心对象交给spring管理.事务由AOP控制 好处: 由java代码进行配置,摆脱硬编码,连接数据库等信息更 ...
- spring 整合hibernate
1. Spring 整合 Hibernate 整合什么 ? 1). 有 IOC 容器来管理 Hibernate 的 SessionFactory2). 让 Hibernate 使用上 Spring 的 ...
- Spring 整合 Hibernate
Spring 整合 Hibernate •Spring 支持大多数流行的 ORM 框架, 包括 Hibernate JDO, TopLink, Ibatis 和 JPA. •Spring 对这些 OR ...
- 使用Spring整合Hibernate,并实现对数据表的增、删、改、查的功能
1.1 问题 使用Spring整合Hibernate,并实现资费表的增.删.改.查. 1.2 方案 Spring整合Hibernate的步骤: 1.3 步骤 实现此案例需要按照如下步骤进行. 采用的环 ...
- Spring整合Hibernate详细步骤
阅读目录 一.概述 二.整合步骤 回到顶部 一.概述 Spring整合Hibernate有什么好处? 1.由IOC容器来管理Hibernate的SessionFactory 2.让Hibernate使 ...
- SSH整合之spring整合hibernate
SSH整合要导入的jar包: MySQL中创建数据库 create database ssh_db; ssh_db 一.spring整合hibernate带有配置文件hibernate.cfg.xml ...
- 【Spring】Spring系列6之Spring整合Hibernate
6.Spring整合Hibernate 6.1.准备工作 6.2.示例 com.xcloud.entities.book com.xcloud.dao.book com.xcloud.service. ...
- 3、Spring整合Hibernate
经过前面的两节分析:1.Hibernate之生成SessionFactory源码追踪 和 2.Spring的LocalSessionFactoryBean创建过程源码分析 .我们可以得到这样一个结论, ...
随机推荐
- c++ map 的基本操作
Map是c++的一个标准容器,她提供了很好一对一的关系,在一些程序中建立一个map可以起到事半功倍的效果,总结了一些map基本简单实用的操作!1. map最基本的构造函数: map<stri ...
- nyoj-71
描述 进行一次独木舟的旅行活动,独木舟可以在港口租到,并且之间没有区别.一条独木舟最多只能乘坐两个人,且乘客的总重量不能超过独木舟的最大承载量.我们要尽量减少这次活动中的花销,所以要找出可以安置所有旅 ...
- Web前端开发基础 第四课(CSS元素模型)
css布局模型 清楚了CSS 盒模型的基本概念. 盒模型类型, 我们就可以深入探讨网页布局的基本模型了.布局模型与盒模型一样都是 CSS 最基本. 最核心的概念. 但布局模型是建立在盒模型基础之上,又 ...
- 安卓中級教程(2):@InjectView中的對象inject
package com.example.ele_me.util; import java.lang.annotation.Annotation; import java.lang.reflect.Fi ...
- git总是出现untracked content怎么解决?
git rm --cached vendor/plugins/open_flash_chart_2 rm -rf vendor/plugins/open_flash_chart_2/.git # BA ...
- php数字操作,高精度函数,保留计算结果小数位
$l = 45456.51; $r = 455778.44; $e = '100.00'; $f= '500.00'; $res = bcadd($l, $r,3);//小数点后的位数,精度就是由这个 ...
- js弹窗
常用人JS弹窗,lhgDialog 4.20
- Any changes made by a writer will not be seen by other users of the database until the changes have been completed
https://en.wikipedia.org/wiki/Multiversion_concurrency_control Multiversion concurrency control (MCC ...
- 【转】NGUI研究院之自适应屏幕(十)
http://www.xuanyusong.com/archives/2536 现在用unity做项目 90%都是用NGUI,并且我个人觉得NGUI应该算是比较成熟的UI插件,虽然他也存在很多问题,但 ...
- Mac OS X系统下利用VirtualBox安装和配置Windows XP虚拟机
准备工作 下载并安装VirtualBox for Mac到https://www.virtualbox.org/wiki/Downloads下载VirtualBox <版本> for OS ...