• 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);
        }
    
    }
  • 相关阅读:
    common-pool2连接池详解与使用
    Nginx实现页面缓存
    Nginx实现动静分离
    lnmp环境下nginx配置‘负载均衡’
    用phpstudy搭建的lnmp环境下mysql授权远程连接
    新浪OAuth网络登录,请求access_token时遇到21323的错误
    使用curl进行模拟登录
    yii2.0分页
    yii2.0表单自带验证码
    yii2.0查询关联数据以及widgets小部件
  • 原文地址:https://www.cnblogs.com/lxnlxn/p/5905412.html
Copyright © 2020-2023  润新知