美文网首页我爱编程
Spring第三天(Spring整合Hibernate)

Spring第三天(Spring整合Hibernate)

作者: 原来蜗牛不是牛 | 来源:发表于2017-07-20 20:21 被阅读0次

    Spring整合Hibernate方式一

    持久层+业务层的整合

    1. 搭建环境,导入Spring和Hibernate的依赖包
    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.10.Final</version>
        </dependency>
        <!-- for JPA, use hibernate-entitymanager instead of hibernate-core -->
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-entitymanager</artifactId>
                <version>5.2.10.Final</version>
            </dependency>
            <!-- optional -->
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-osgi</artifactId>
                <version>5.2.10.Final</version>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-envers</artifactId>
                <version>5.2.10.Final</version>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-c3p0</artifactId>
                <version>5.2.10.Final</version>
            </dependency>
    
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-proxool</artifactId>
                <version>5.2.10.Final</version>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-infinispan</artifactId>
                <version>5.2.10.Final</version>
            </dependency>
            <dependency>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-ehcache</artifactId>
                <version>5.2.10.Final</version>
            </dependency>
        <!-- 添加Spring包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency> 
        
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        
        <!-- 为了方便进行单元测试,添加spring-test包 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.6.RELEASE</version>
        </dependency>
        <!--添加aspectjweaver包 -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.5</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
    
    1. 根据需求做设计
      数据库设计
      文档:
      概要设计:功能点列出来。
      详细设计,接口层面(定义的类,方法,参数)
      ...
      创建一个汽车表t_car
    DROP TABLE IF EXISTS `t_car`;
    CREATE TABLE `t_car` (
      `cid` bigint(11) NOT NULL AUTO_INCREMENT,
      `name` varchar(20) NOT NULL,
      `color` varchar(10) NOT NULL,
      `description` varchar(100) NOT NULL,
      PRIMARY KEY (`cid`)
    ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
    INSERT INTO `t_car` VALUES ('1', '兰博基尼', '绿色', '无限拉风的车子,无限装逼的车子');
    INSERT INTO `t_car` VALUES ('3', '玛莎拉蒂', '蓝色', '千里马常有,而伯乐不常有');
    INSERT INTO `t_car` VALUES ('4', '大众', '黑色', '千里马常有,而伯乐不常有');
    
    1. 创建Hibernate核心配置文件
      下面介绍一下怎么使用Hibernate Tools插件生成Hibernate的配置文件,映射文件以及实体类
    • 安装Hibernate Tools插件
      到eclipse的商店里面安装jboss插件,jboss是很多插件整合在一起,我们只使用Hibernate Tools就可以了,所以在安装的时候记得只勾选Hibernate就行了
      Hibernate Tools
    • 创建Hibernate核心配置文件(hibernate.cfg.xml)
      把四大属性和方言配置好,其他属性按需要配置
      hibernate.cfg.xml
    • 创建hiberenate的映射文件和实体类POJO
      因为数据库的表已经创建好了,我们可以根据表来反转创建映射文件和实体类,具体操作如下:
      • 先创建反转文件


        reveng.xml
      • 进行反转配置界面


        Go

    上面那个点击的图标可能没有,点击Window-Perspective-Custormize Perspective...-Action Set Availability勾选上Hibernate Code Generation即可
    + 配置


    配置
    配置

    配置完成点击Run,自动生成映射文件和实体类
    实体类:

    public class TCar implements Serializable {
        private Long cid;
        private String name;
        private String color;
        private String description;
          //getter setter方法
    }
    

    映射文件:(注意将映射文件注册到hibernate核心配置文件中去)

    <hibernate-mapping auto-import="true" default-access="property" default-cascade="none" default-lazy="true">
        <class catalog="spring" dynamic-insert="false" dynamic-update="false" mutable="true" name="com.cx.model.TCar" optimistic-lock="version" polymorphism="implicit" select-before-update="false" table="t_car">
            <id name="cid" type="java.lang.Long">
                <column name="cid"/>
                <generator class="identity"/>
            </id>
            <property generated="never" lazy="false" name="name" optimistic-lock="true" type="string" unique="false">
                <column length="20" name="name" not-null="true"/>
            </property>
            <property generated="never" lazy="false" name="color" optimistic-lock="true" type="string" unique="false">
                <column length="10" name="color" not-null="true"/>
            </property>
            <property generated="never" lazy="false" name="description" optimistic-lock="true" type="string" unique="false">
                <column length="100" name="description" not-null="true"/>
            </property>
        </class>
    </hibernate-mapping>
    
    • 创建持久层的接口和实现类
      接口:
    public interface CarDao {
        void addCar(TCar car);
        
        void deleteCar(Long id);
        
        void updateCar(Long id,String color);
        
        TCar findById(Long id);
    }
    

    实现类:
    使用 Spring提供的模板类来整合持久层
    不用写工具类:先得到SessionFactory再得到session
    交给Spring.
    使用了HibernateTemplate,本质上还是使用了Session.

    public class CarDaoImpl implements CarDao {
        private HibernateTemplate ht;
        
        public void setHt(HibernateTemplate ht) {
            this.ht = ht;
        }
    
        @Override
        public void addCar(TCar car) {
            ht.save(car);
        }
    
        @Override
        public void deleteCar(Long id) {
            ht.delete(ht.get(TCar.class, id));
        }
    
        @Override
        public void updateCar(Long id, String color) {
            TCar car = ht.get(TCar.class, id);
            car.setColor(color);
            ht.update(car);
        }
    
        @Override
        public TCar findById(Long id) {
            
            return ht.get(TCar.class, id);
        }
    }
    
    • 开发业务层接口和实现类
      接口:
    public interface CarService {
        void addCar(TCar car);
        
        void deleteCar(Long id);
        
        void updateCar(Long id,String color);
        
        TCar findById(Long id);
    }
    

    实现类:

    public class CarServiceImpl implements CarService {
        private CarDao carDao;
        
        public void setCarDao(CarDao carDao) {
            this.carDao = carDao;
        }
    
        @Override
        public void addCar(TCar car) {
            carDao.addCar(car);
        }
    
        @Override
        public void deleteCar(Long id) {
            carDao.deleteCar(id);
    
        }
    
        @Override
        public void updateCar(Long id, String color) {
            carDao.updateCar(id, color);
    
        }
    
        @Override
        public TCar findById(Long id) {
            
            return carDao.findById(id);
        }
    }
    
    • Spring整合持久层Hibernate配置
      Spring提供创建SessionFactory的Bean.(以前我们是使用工具类来创建的。)


      Spring-Hibernate
    <!-- 1. 由Spring来创建SessionFactory -->
        <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" >
            <!-- 读取配置文件 -->
            <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
        </bean>
        <!-- 2.创建Spring提供的HiberanteTemplate模板对象,同时注入sessionFactory -->
        <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate" >
            <property name="sessionFactory" ref="sessionFactory"></property>
        </bean>
        <!-- 3.创建DAO对象,注入hibernateTemplate  dao就具备session能力  -->
        <bean id="carDao" class="com.cx.dao.impl.CarDaoImpl" >
            <property name="ht" ref="hibernateTemplate"></property>
        </bean> 
        <!-- 4.创建服务层对象,注入dao  -->
        <bean id="carService" class="com.cx.service.impl.CarServiceImpl" >
            <property name="carDao" ref="carDao"></property>
        </bean>
    

    经过上面的配置,可以进行测试,但是只能进行查询的操作,因为增、删、改的操作必须要在事务环境下才能执行,所以下面通过AOP编程配置事务

    配置事务

    需要数据源对象


    image.png

    在上面配置的基础上添加下面的配置(事务配置)

    <!-- 0.创建ComboPooledDataSource对象 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"></bean>
    <!-- 5.创建Spring提供的事务管理通知对象 -->
        <bean id="txManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager" >
            <property name="sessionFactory" ref="sessionFactory"></property>
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <!-- 6.配置Spring提供的事务通知切面 -->
        <tx:advice id="txAdvice" transaction-manager="txManager" >
            <tx:attributes>
                <tx:method name="add*" propagation="REQUIRED"/>
                <tx:method name="delete*" propagation="REQUIRED"/>
                <tx:method name="update*" propagation="REQUIRED"/>
            </tx:attributes>
        </tx:advice>
        <!-- 7.AOP编程 -->
        <aop:config>
            <aop:pointcut expression="execution(* com.cx.service.*.*(..))" id="shpoint"/>
            <aop:advisor advice-ref="txAdvice" pointcut-ref="shpoint"/>
        </aop:config>
    

    事务配置也可使用注解配置,只需将上面配置的6,7去掉,添加

    <!-- 6,7配置注解的AOP驱动,关联事务管理通知类 -->
        <tx:annotation-driven transaction-manager="txManager"/>
    

    在需要事务的类上添加注解:

    @Transactional(value="txManager")
    public class CarDaoImpl implements CarDao {...}
    

    测试类如下:

    public class Test {
        public static void main(String[] args) {
            ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext2.xml");
            CarService carService = ac.getBean("carService",CarService.class);
            //查询
            /*TCar car = carService.findById(1L);
            System.out.println(car.getName()+"\t"+car.getColor()+"\t"+car.getDescription());*/
            //增加
            TCar car = new TCar();
            car.setName("大众");
            car.setColor("黑色");
            car.setDescription("千里马常有,而伯乐不常有");
            carService.addCar(car);
            //修改
            //carService.updateCar(3L, "蓝色");
            //删除
            //carService.deleteCar(2L);
        }
    }
    

    相关文章

      网友评论

        本文标题:Spring第三天(Spring整合Hibernate)

        本文链接:https://www.haomeiwen.com/subject/opnlkxtx.html