您的位置:首页 > 编程语言 > Java开发

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

2017-12-10 19:14 489 查看


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");
}
}




当钱不够的时候,会抛出异常“余额不足”,并且事务回滚;当钱足够时,正常执行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: