SpringAOP整合Hibernate并使用事务(模拟买书的过程)
来源:互联网 发布:linux 访问smb 编辑:程序博客网 时间:2024/06/06 04:33
SpringAOP整合Hibernate并使用事务(模拟买书的过程)
1.内容准备
①.编写实体类
Book
public class Book { public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getCount() { return count; } public void setCount(int count) { this.count = count; } private int id; private String name; private int price; private int count;}
Customer
public class Customer { public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getBalance() { return balance; } public void setBalance(int balance) { this.balance = balance; } private int id; private String name; private int balance;}
②.编写实体类映射文件
<hibernate-mapping package="springaop.model"> <class name="Book" table="t_book"> <id name="id" type="int" column="id" > <generator class="native"></generator> </id> <property name="name" type="string" column="name"/> <property name="price" type="int" column="price"/> <property name="count" type="int" column="count"/> </class></hibernate-mapping>
<hibernate-mapping package="springaop.model"> <class name="Customer" table="t_customer"> <id name="id" type="int" column="id" > <generator class="native"></generator> </id> <property name="name" type="string" column="name"/> <property name="balance" type="int" column="balance"/> </class></hibernate-mapping>
③.编写dao及daoImpl
public interface ShopRepository { public int findBookPriceByBookName(String name); public void updateBookCount(String name); public void updateUserBalance(String name,int price);}
@Repositorypublic class ShopRepositoryImpl implements ShopRepository{ @Autowired private SessionFactory sessionFactory; private Session getSession(){ return sessionFactory.getCurrentSession(); } @Override public int findBookPriceByBookName(String name) { String sql = "select b.price from Book b where b.name=?"; Query query = getSession().createQuery(sql).setString(0, name); return (Integer)query.uniqueResult(); } @Override public void updateBookCount(String name) { String sql1 = "select b.count from Book b where b.name=?"; Query query = getSession().createQuery(sql1).setString(0,name); int count = (int)query.uniqueResult(); if(count<=0){ throw new RuntimeException("库存不足"); } String sql2 = "update Book b set b.count=b.count-1 where b.name=?"; getSession().createQuery(sql2).setString(0,name).executeUpdate(); } @Override public void updateUserBalance(String name, int price) { String sql1 = "select c.balance from Customer c where c.name=?"; Query query = getSession().createQuery(sql1).setString(0,name); int count = (int)query.uniqueResult(); if(count-price<0){ throw new RuntimeException("余额不足"); } String sql2 = "update Customer c set c.balance=c.balance-? where c.name=?"; getSession().createQuery(sql2).setInteger(0, price).setString(1,name).executeUpdate(); }}
④.编写service及serviceImpl
public interface ShopService { public void shop(String bookName,String username);}
@Servicepublic class ShopServiceImpl implements ShopService{ @Autowired private ShopRepository sr; @Override public void shop(String bookName, String username) { int price = sr.findBookPriceByBookName(bookName); sr.updateUserBalance(username, price); sr.updateBookCount(bookName); }}
2.加入Hibernate
①.添加hibernate必须的jar包
②.添加hibernate.cfg.xml
<hibernate-configuration> <session-factory> <!-- 配置hibernate的基本属性 --> <!-- 1.数据源的配置,配置到SpringIOC中,此处不需要再进行配置 --> <!-- 2.关联实体的映射文件 .hbm.xml文件也在IOC容器配置SessionFactory实例时配置 --> <!-- 3.配置hibernate的基本属性 方言、sql显示及格式化、数据库表生成策略、二级缓存--> <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <!-- 配置hibernate二级缓存相关 --> </session-factory></hibernate-configuration>
3.加入Spring
①.导入Spring必须的jar包
②.配置Spring的applicationContext.xml及db.properties文件
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.1.xsd " xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" > <!-- 配置Spring扫描的包 --> <context:component-scan base-package="springaop"></context:component-scan> <!-- 配置数据源 --> <!-- 导入资源文件 --> <context:property-placeholder location="classpath:db.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.initialPoolSize}"></property> <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property> </bean> <!-- 配置Hibernete的SessionFactory实例 --> <!-- 通过配置Spring提供的LcalSessionFactory --> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> <property name="mappingLocations" value="classpath:springaop/model/*.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="*"/> </tx:attributes> </tx:advice> <!-- 3.配置事务切点,并把切点和事务关联起来, --> <aop:config> <aop:pointcut expression="execution(* springaop.service.*.*(..))" id="txPointcut"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/> </aop:config> </beans>
jdbc.user=rootjdbc.password=1234jdbc.driverClass=com.mysql.jdbc.Driverjdbc.jdbcUrl=jdbc:mysql:///testjdbc.initialPoolSize=5jdbc.maxPoolSize=10
4.运行测试
public class test { private ApplicationContext context = null; private ShopService ss = null; { context = new ClassPathXmlApplicationContext("applicationContext.xml"); ss= context.getBean(ShopService.class); } @Test public void test() throws SQLException{ DataSource ds = context.getBean(DataSource.class); System.out.println(ds.getConnection()); } @Test public void test1(){ ss.shop("Java", "jayjay"); } @Test public void test3(){ ss.shop("C", "jayjay"); }}
当钱不够的时候,会抛出异常“余额不足”,并且事务回滚;当钱足够时,正常执行。
阅读全文
0 0
- SpringAOP整合Hibernate并使用事务(模拟买书的过程)
- Spring 对hibernate事务处理的实现过程(2) spring怎么获取hibernate使用的session并开启事务的
- SpringAOP的实现过程
- springAOP 实现事务的管理
- Spring整合Hibernate事务
- SpringAop的使用
- Spring整合hibernate的事务属性介绍以及声明式事务管理 (使用Annotation和xml)
- Spring整合hibernate的事务属性介绍以及声明式事务管理 (使用Annotation和xml)
- SpringAOP声明式事务的一个缺陷
- Xfire 整合spring和hibernate的过程
- struts2,spring整合中使用spring 管理struts2的action,springaop 常见问题
- hibernate 存储过程事务
- 存储过程、事务的使用
- 存储过程事务的使用
- springmvc+hibernate整合事务不回滚
- spring-hibernate整合 事务不起作用
- SpringAop切面的简单使用
- SpringAOP环绕通知的使用
- 浅谈C/C++排序函数中cmp()比较函数的写法
- from表单+地区
- eclipse打点没提示原因
- 菜鸟备忘录[CSS3]——媒体查询使用方法@media
- CodeForces 830C Bamboo Partition
- SpringAOP整合Hibernate并使用事务(模拟买书的过程)
- kuangbin专题五 并查集 POJ2236-Wireless Network
- UE4 C++创建删除文件夹(对本地文件夹进行操作)
- shell
- Docker: 精通ENTRYPOINT指令
- 栈的基本操作
- 给你一台大疆无人机,你能用来做点啥?(三)------倾斜摄影建模基础
- Eclipse 创建一个项目 并使用 git 上传到 码云
- jQuery添加删除,全选反选,批量删除