spring4整合hibernate5.1

在另一篇文章hibernate5(2)初入门配置实例中,我们针对hibernate5.1版本的崭新引导配置方法,完成了对数据库的的插入实例操作,在本节内容中,我们开始引入spring4,完成spring4与hibernate5.1的整合工作,像数据库中插入一条记录。在后面学习hibernate中,我们都会使用spring来管理我们的Bean容器。

1. 导入spring4所需jar包

我们推荐使用maven来管理项目,下面是maven中的spring整合hibernate完整配置。

<properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <org.hibernate-version>5.1.0.Finalorg.hibernate-version>
    
    <spring.version>4.0.2.RELEASEspring.version>
properties>
<dependencies>
    <dependency>
        <groupId>junitgroupId>
        <artifactId>junitartifactId>
        <version>4.10version>
        <scope>testscope>
    dependency>
    <dependency>
        <groupId>org.slf4jgroupId>
        <artifactId>slf4j-apiartifactId>
        <version>1.7.5version>
    dependency>
    <dependency>
        <groupId>org.slf4jgroupId>
        <artifactId>slf4j-log4j12artifactId>
        <version>1.7.5version>
        <scope>runtimescope>
    dependency>
    <dependency>
        <groupId>log4jgroupId>
        <artifactId>log4jartifactId>
        <version>1.2.17version>
        <scope>runtimescope>
    dependency>
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>5.1.21version>
    dependency>
    <dependency>
        <groupId>cglibgroupId>
        <artifactId>cglibartifactId>
        <version>2.2.2version>
    dependency>
    
    <dependency>
        <groupId>commons-dbcpgroupId>
        <artifactId>commons-dbcpartifactId>
        <version>1.2.2version>
    dependency>
    
    <dependency>
        <groupId>org.hibernategroupId>
        <artifactId>hibernate-coreartifactId>
        <version>${org.hibernate-version}version>
    dependency>
    <dependency>
        <groupId>org.hibernategroupId>
        <artifactId>hibernate-validatorartifactId>
        <version>${org.hibernate-version}version>
    dependency>
    
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-coreartifactId>
        <version>${spring.version}version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-webartifactId>
        <version>${spring.version}version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-ormartifactId>
        <version>${spring.version}version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-txartifactId>
        <version>${spring.version}version>
    dependency>

    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-jdbcartifactId>
        <version>${spring.version}version>
    dependency>

    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-webmvcartifactId>
        <version>${spring.version}version>
    dependency>
    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-aopartifactId>
        <version>${spring.version}version>
    dependency>

    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-context-supportartifactId>
        <version>${spring.version}version>
    dependency>

    <dependency>
        <groupId>org.springframeworkgroupId>
        <artifactId>spring-testartifactId>
        <version>${spring.version}version>
    dependency>
    
    
    <dependency>
        <groupId>javax.servletgroupId>
        <artifactId>javax.servlet-apiartifactId>
        <version>3.1.0version>
        <scope>providedscope>
    dependency>
    <dependency>
        <groupId>org.apache.commonsgroupId>
        <artifactId>commons-dbcp2artifactId>
        <version>2.0version>
    dependency>
    <dependency>
        <groupId>commons-logginggroupId>
        <artifactId>commons-loggingartifactId>
        <version>1.1.1version>
    dependency>
dependencies>

在这里,我们顺便引入了springMVC相关jar包,在我们的后续学习测试中可能会用到,现在暂时不用理会

2. 编写spring容器文件

在上一节中,我们的数据库、hibernate的相关配置都在hibernate.cfg.xml文件中完整,使用spring后,这些统统交给spring来进行管理。spring完整实例配置文件如下


<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="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-3.0.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close"> 
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/yc" />
        <property name="username" value="yc" />
        <property name="password" value="yc" />
        <property name="defaultReadOnly" value="false" />
        <property name="initialSize" value="5" />
        <property name="maxActive" value="15" />
        <property name="maxIdle" value="10"/>
        <property name="minIdle" value="2" />
        <property name="maxWait" value="10000" />
    bean>
    
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource" />
        property>
        <property name="hibernateProperties">
            <props>
                
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialectprop>
                <prop key="javax.persistence.validation.mode">noneprop>
                
                <prop key="hibernate.hbm2ddl.auto">updateprop>
                <prop key="hibernate.show_sql">trueprop>
                
                <prop key="current_session_context_class">threadprop>
                
                
            props>
        property>
        <property name="packagesToScan" value="com.zeng.model" />
    bean>
beans>

关于spring的配置学习,可参考我另一博客专栏《Spring研磨分析》。

3. 编写测试实体类

测试实体类与我们上一篇文章实例一样。

package com.zeng.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity//声明当前类为hibernate映射到数据库中的实体类
@Table(name = "t_user")//声明在数据库中自动生成的表名为t_user
public class User {
    @Id//声明此列为主键
    @GeneratedValue(strategy = GenerationType.AUTO)//根据不同数据库自动选择合适的id生成方案,这里使用mysql,为递增型
    private Integer id;
    private String name;
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

4. 编写测试方法

@Test
public void test2(){
    //使用此方法获取并初始化我们的spring容器,注意pring-datasource.xml必须存放在类路径的根目录下。
    ApplicationContext ac = new ClassPathXmlApplicationContext("spring-datasource.xml");
    //从spring容器中获取我们的会话工厂实例,里面已完成好各个属性的配置工作
    SessionFactory sessionFactory = (SessionFactory) ac.getBean("sessionFactory");

    //下面开始我们的数据库操作
    Session session = sessionFactory.openSession();//从会话工厂获取一个session
    Transaction transaction = session.beginTransaction();//开启一个新的事务
    User user = new User();
    user.setName("hello spring");
    session.save(user);
    transaction.commit();//提交事务
}

运行测试文件,看到打印信息:
Hibernate: insert into t_user (name) values (?)
说明我们的插入操作已完成,查看数据,会看到一条新的记录。

至此,我们轻松地完成了spring与hibernate的整合工作,从下一节开始,我们以快速入门为目的,先介绍hibernate的各类使用方法,在结合实例熟悉hibernate的基本使用后,我们再深入开展对hibernate的分析学习。

源码下载

本实例源码可到https://github.com/jeanhao/hibernate下载。

你可能感兴趣的:(javaweb,spring,hibernate,Spring研磨分析,hibernate示例解析,数据库,java,hibernate5,spring4,ssh)