SpringAOP整合Hibernate并使用事务(模拟买书的过程)

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);
}
复制代码
@Repository
public 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);
}
复制代码
@Service
public 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=root
jdbc.password=1234
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///test

jdbc.initialPoolSize=5
jdbc.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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值