Spring 教程05

spring-5
1.    Xml

<!-- \src\applicationContext.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 配置自动扫描的包 -->
    <context:component-scan base-package="com.atguigu.spring.hibernate"></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.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>
        -->
        <!-- 使用 hibernateProperties 属相来配置 Hibernate 原生的属性 -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>
        <!-- 配置 hibernate 映射文件的位置及名称, 可以使用通配符 -->
        <property name="mappingLocations"
            value="classpath:com/atguigu/spring/hibernate/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.spring.hibernate.service.*.*(..))"
            id="txPointcut"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
    </aop:config>

</beans>

<!-- \src\com\atguigu\spring\hibernate\entities\Account.hbm.xml -->
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.atguigu.spring.hibernate.entities.Account" table="SH_ACCOUNT">

        <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>

<!-- \src\com\atguigu\spring\hibernate\entities\Book.hbm.xml -->
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.atguigu.spring.hibernate.entities.Book" table="SH_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.cfg.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<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>

2.    Properties

# \src\db.properties
jdbc.user=root
jdbc.password=1230
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///spring7

jdbc.initPoolSize=5
jdbc.maxPoolSize=10
#...
3.    Java

// \src\com\atguigu\spring\hibernate\dao\BookShopDao.java
package com.atguigu.spring.hibernate.dao;

public interface BookShopDao {

    //根据书号获取书的单价
    public int findBookPriceByIsbn(String isbn);

    //更新数的库存. 使书号对应的库存 - 1
    public void updateBookStock(String isbn);

    //更新用户的账户余额: 使 username 的 balance - price
    public void updateUserAccount(String username, int price);
}

// \src\com\atguigu\spring\hibernate\dao\impl\BookShopDaoImpl.java
package com.atguigu.spring.hibernate.dao.impl;

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.spring.hibernate.dao.BookShopDao;
import com.atguigu.spring.hibernate.exceptions.BookStockException;
import com.atguigu.spring.hibernate.exceptions.UserAccountException;

@Repository
public class BookShopDaoImpl implements BookShopDao {

    @Autowired
    private SessionFactory sessionFactory;

    //不推荐使用 HibernateTemplate 和 HibernateDaoSupport
    //因为这样会导致 Dao 和 Spring 的 API 进行耦合
    //可以移植性变差
//  private HibernateTemplate hibernateTemplate;

    //获取和当前线程绑定的 Session.
    private Session getSession(){
        return sessionFactory.getCurrentSession();
    }

    @Override
    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();
    }

    @Override
    public void updateBookStock(String isbn) {
        //验证书的库存是否充足.
        String hql2 = "SELECT b.stock FROM Book b WHERE b.isbn = ?";
        int stock = (int) getSession().createQuery(hql2).setString(0, isbn).uniqueResult();
        if(stock == 0){
            throw new BookStockException("库存不足!");
        }

        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 = (int) getSession().createQuery(hql2).setString(0, username).uniqueResult();
        if(balance < price){
            throw new UserAccountException("余额不足!");
        }

        String hql = "UPDATE Account a SET a.balance = a.balance - ? WHERE a.username = ?";
        getSession().createQuery(hql).setInteger(0, price).setString(1, username).executeUpdate();
    }

}

// \src\com\atguigu\spring\hibernate\entities\Account.java
package com.atguigu.spring.hibernate.entities;

public class Account {

    private Integer id;
    private String username;
    private int balance;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getBalance() {
        return balance;
    }

    public void setBalance(int balance) {
        this.balance = balance;
    }

}

// \src\com\atguigu\spring\hibernate\entities\Book.java
package com.atguigu.spring.hibernate.entities;

public class Book {

    private Integer id;
    private String bookName;
    private String isbn;
    private int price;
    private int stock;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public String getIsbn() {
        return isbn;
    }

    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

    public int getStock() {
        return stock;
    }

    public void setStock(int stock) {
        this.stock = stock;
    }

}

// \src\com\atguigu\spring\hibernate\exceptions\BookStockException.java
package com.atguigu.spring.hibernate.exceptions;

public class BookStockException extends RuntimeException{

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public BookStockException() {
        super();
        // TODO Auto-generated constructor stub
    }

    public BookStockException(String message, Throwable cause,
            boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
        // TODO Auto-generated constructor stub
    }

    public BookStockException(String message, Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

    public BookStockException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

    public BookStockException(Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }

}

// \src\com\atguigu\spring\hibernate\exceptions\UserAccountException.java
package com.atguigu.spring.hibernate.exceptions;

public class UserAccountException extends RuntimeException{

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    public UserAccountException() {
        super();
        // TODO Auto-generated constructor stub
    }

    public UserAccountException(String message, Throwable cause,
            boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
        // TODO Auto-generated constructor stub
    }

    public UserAccountException(String message, Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

    public UserAccountException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

    public UserAccountException(Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }

}

// \src\com\atguigu\spring\hibernate\service\BookShopService.java
package com.atguigu.spring.hibernate.service;

public interface BookShopService {

    public void purchase(String username, String isbn);

}

// \src\com\atguigu\spring\hibernate\service\Cashier.java
package com.atguigu.spring.hibernate.service;

import java.util.List;

public interface Cashier {

    public void checkout(String username, List<String> isbns);

}

// \src\com\atguigu\spring\hibernate\service\impl\BookShopServiceImpl.java
package com.atguigu.spring.hibernate.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.atguigu.spring.hibernate.dao.BookShopDao;
import com.atguigu.spring.hibernate.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
     */
    @Override
    public void purchase(String username, String isbn) {
        int price = bookShopDao.findBookPriceByIsbn(isbn);
        bookShopDao.updateBookStock(isbn);
        bookShopDao.updateUserAccount(username, price);
    }

}

// \src\com\atguigu\spring\hibernate\service\impl\CashierImpl.java
package com.atguigu.spring.hibernate.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.atguigu.spring.hibernate.service.BookShopService;
import com.atguigu.spring.hibernate.service.Cashier;

@Service
public class CashierImpl implements Cashier{

    @Autowired
    private BookShopService bookShopService;

    @Override
    public void checkout(String username, List<String> isbns) {
        for(String isbn:isbns){
            bookShopService.purchase(username, isbn);
        }
    }

}

// \src\com\atguigu\spring\hibernate\test\SpringHibernateTest.java
package com.atguigu.spring.hibernate.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.spring.hibernate.service.BookShopService;
import com.atguigu.spring.hibernate.service.Cashier;

public class SpringHibernateTest {

    private ApplicationContext ctx = null;
    private BookShopService bookShopService = null;
    private Cashier cashier = null;

    {
        ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        bookShopService = ctx.getBean(BookShopService.class);
        cashier = ctx.getBean(Cashier.class);
    }

    @Test
    public void testCashier(){
        cashier.checkout("aa", Arrays.asList("1001","1002"));
    }

    @Test
    public void testBookShopService(){
        bookShopService.purchase("aa", "1001");
    }

    @Test
    public void testDataSource() throws SQLException {
        DataSource dataSource = ctx.getBean(DataSource.class);
        System.out.println(dataSource.getConnection());
    }

}
时间: 2024-07-30 07:21:00

Spring 教程05的相关文章

Angular系列----AngularJS入门教程05:双向绑定(转载)

在这一步你会增加一个让用户控制手机列表显示顺序的特性.动态排序可以这样实现,添加一个新的模型属性,把它和迭代器集成起来,然后让数据绑定完成剩下的事情. 请重置工作目录: git checkout -f step-4 你应该发现除了搜索框之外,你的应用多了一个下来菜单,它可以允许控制电话排列的顺序. 步骤3和步骤4之间最重要的不同在下面列出.你可以在GitHub里看到完整的差别. 模板 app/index.html Search: <input ng-model="query"&g

Spring(05)IoC 依赖查找

目录 Spring(05)IoC 依赖查找 1. 依赖查找的今世前生 2. 单一类型依赖查找 3. 集合类型依赖查找 4. 层次性依赖查找 5. 延迟依赖查找 6. 安全依赖查找 7. 内建可查找的依赖 8. 依赖查找中的经典异常 9. 面试题精选 Spring(05)IoC 依赖查找 Spring 核心编程思想目录:https://www.cnblogs.com/binarylei/p/12290153.html 1. 依赖查找的今世前生 单一类型依赖查找 JNDI:javax.naming.

Spring教程:tutorialspoint-spring

来自turorialspoint的Maven教程(英文),官网:https://www.tutorialspoint.com/spring/index.htm 这个教程在国内已经被翻译成中文(不过是属于机器翻译),官网:http://wiki.jikexueyuan.com/project/spring/ 离线版本:链接:http://pan.baidu.com/s/1miJUM5i 密码:qj4q 总结: 1.本书比较容易上手,功能点达到中级,不会讲解升深入的难点,基本把Spring中级的功能

Spring 教程(四) Hello World 实例

Hello World 实例 让我们使用 Spring 框架开始实际的编程.在你开始使用 Spring 框架编写第一个例子之前,你必须确保已经正确地设置了 Spring 环境,正如在 Spring——环境设置 教程中如所说的.假设你有了解一些有关 Eclipse IDE 工作的知识. 因此,让我们继续编写一个简单的 Spring 应用程序,它将根据在 Spring Beans 配置文件中配置的信息输出 “Hello World!” 或其他信息. 第 1 步:创建 Java 项目 第一步是使用 E

Spring 教程(三) 环境设置

环境设置 本教程将指导你如何准备开发环境来使用 Spring 框架开始你的工作.本教程还将教你在安装 Spring 框架之前如何在你的机器上安装 JDK,Tomcat 和 Eclipse. 第 1 步:安装 Java 开发工具包(JDK) 你可以从 Oracle 的 Java 网站 Java SE Downloads 下载 SDK 的最新版本.你会在下载的文件中找到教你如何安装 JDK 的说明,按照给出的说明安装和配置 JDK 的设置.最后,设置 PATH 和 JAVA_HOME 环境变量,引入

spring教程

Spring框架是Java EE开发中最流行的框架,已经成为JEE事实上的标准,全世界的开发人员都在使用Spring框架开发各种应用.随着Spring boot,Spring cloud新版本的不断推出,以及微服务的流行,Spring已经成为JEE开发"必修"项目. 本教程介绍spring框架的核心概念:DI.AOP等.本教程遵循二八原则(80%的场景只会用到20%的技术,也就是说大多数场景只会用少最常用的技术),我们只讲最重要最常用的部分,让你不走弯路,花最少时间学到最多. Spri

【spring教程之四】spring中bean的作用域

1. <bean id="stage" class="com.test.pro.Stage"> 在spring中,bean默认都是单例的,也就是说,spring容易只会实例化一次,在以后的每次调用中,都会使用同一个实例.下面的例子可以说明: 2.测试类 package com.test.pro; import org.springframework.context.ApplicationContext; import org.springframewor

【spring教程之八】spring自动装配

1.在我们之间的spring装配中,如果一个bean用到了另外一个bean文件,那么格式应该是这样的: <!-- 主bean --> <bean id="A" class="com.test.pro.Singer"> <property name="myb" ref="B"></property> </bean> <!-- 被装配的bean --> <

MyBatis 教程05

<!-- \build\classes\applicationContext.xml --> <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" x