SpringMVC+Hibernate

6 篇文章 0 订阅
3 篇文章 0 订阅

本文介绍一下如何在SpringMVC项目基础上整合Hibernate。

本文采用的是Spring 4.1.9+Hibernate4.3.11+Maven

开发工具采用MyEclipse 2014

本文的目标是搭建简单的SpringMVC+Spring+Hibernate+MySQL的开发环境,最终由Hibernate直接生成数据库中的数据表。

完整代码可参见:http://code.taobao.org/p/smvc_for_jiisb/src/smvc/
加入必要的Maven dependency

 <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.1.9.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.26</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.11.Final</version>
        </dependency>

spring-orm:是spring对ORM支持的包。我们知道Hibernate就是提供ORM功能的,既然要用Spring管理Hibernate,自然要加入Spring的ORM支持包。

mysql-connector-java:是MySQL官方提供的java访问和操作MySQL数据库的包。

druid:是阿里巴巴提供的数据库连接池的包。阿里很牛,支持阿里。

hibernate-core:是hibernate的核心包。

设置web.xml,spring.xml等配置文件

由于加入了spring,因此需要在web.xml中增加spring的监听器,这个配置是spring启动的基础。

注意:这里配置的是spring,与springmvc的配置是两回事儿。

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
     </context-param>

     <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
     </listener>

上面的配置增加到web.xml中即可。

首先创建了一个全局变量contextConfigLocation,这个变量指向的是classpath文件夹下的spring.xml文件。

1474898515444058446.png classpath在哪儿呢?

classpath文件就是Web项目编译后的WEB-INF/classes文件夹。

在项目中的src之类的源文件夹编译后都会放到classes文件夹下。

因此知道,下一步要在src源文件夹下创建一个spring.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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd
      http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:annotation-config />

    <context:component-scan base-package="com.jiisb.app">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!-- 导入spring的其他配置文件 -->
    <import resource="classpath:spring-*.xml" />

</beans>

这是整个spring项目最重要的配置文件,是一切spring配置文件的入口文件。

context:annotaion-config:定义了该spring支持注解;

context:componet-scan:定义了在哪个包及其子包中找被注解的类;

context:exclude-filter:定义不包含那些注解

import:是说导入的其他spring的配置文件规则

至此,spring的基本配置完成了。接下来就要准备Hibernate的配置了。

配置数据源和SessionFactory

在src源文件夹下创建一个spring-datasource.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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <bean id="mydatasource" class="com.alibaba.druid.pool.DruidDataSource"
        init-method="init" destroy-method="close">
        <!-- 数据库驱动 -->
        <!-- 连接URL串 -->
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/test" />
        <!-- 连接用户名 -->
        <property name="username" value="root" />
        <!-- 连接密码 -->
        <property name="password" value="111111" />
        <property name="maxActive" value="50" />
        <property name="initialSize" value="2" />
        <property name="maxWait" value="60000" />
        <property name="minIdle" value="2" />

        <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->

        <property name="timeBetweenEvictionRunsMillis" value="10000" />
        <property name="minEvictableIdleTimeMillis" value="30000" />
        <property name="validationQuery" value="SELECT 'x'" />
        <property name="testWhileIdle" value="true" />
        <property name="testOnBorrow" value="false" />
        <property name="testOnReturn" value="false" />
        <property name="poolPreparedStatements" value="true" />
        <property name="maxPoolPreparedStatementPerConnectionSize" value="50" />
    </bean>

</beans>

这是利用druid创建了一个数据源。

接下来配置Hibernate的SessionFactory,在src文件夹下创建spring-hibernate.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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.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
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd
      http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">

    <context:annotation-config />

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="mydatasource"/>
        <property name="hibernateProperties">
            <props>
                <!-- 数据库方言 -->
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.MySQL5InnoDBDialect
                </prop>
                <!-- 项目启动是否就创建出来bean对应的数据表 -->
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
        <!-- 你的bean都放哪儿了 -->
        <property name="packagesToScan">
            <list>
                <value>com.jiisb.app.entity</value>
            </list>
        </property>

    </bean>



</beans>

这段配置定义了sessionFactory,是Hibernate操作的核心对象,该对象维护了访问和操作数据库的功能。

packageToScan:定义了在哪个包下扫描实体类。

编写测试实体

在com.jiisb.app.entity包下创建一个Article实体类,该实体类对应数据库test中的t_article表,不过我们不在数据库中创建t_article数据表,而是由Hibernate生成t_article数据表。

package com.jiisb.app.entity;

import java.util.Date;

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


@Entity  //声明该类是一个实体
@Table(name="t_article")   //声明对应数据库中的表名
public class Article {


    @Id   // 该字段是一个主键
   @GeneratedValue(strategy=GenerationType.IDENTITY)   // 主键值生成规则是自增的
    @Column(name="noid")   // 字段名为noid
    private Integer noid;

    @Column(name="title",length=200)  //字段名为title,长度为200
    private String title;

    @Column(name="content",length=2000)
    private String content;

    @Column(name="update_date")  // 字段名为update_date
    private Date updateDate;

    public Integer getNoid() {
        return noid;
    }

    public void setNoid(Integer noid) {
        this.noid = noid;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Date getUpdateDate() {
        return updateDate;
    }

    public void setUpdateDate(Date updateDate) {
        this.updateDate = updateDate;
    }

}

项目至此创建完毕,部署到tomcat中并启动,执行完毕后,将看到数据库中创建了数据表t_article,说明项目创建成功。

[1476362202601088554.png] 向数据表中插入一条记录

本项目是基于SpringMVC的,因此最合适的测试方式是在Controller层增加一个方法,该方法可以通过/test/index.do的URL访问,在这个方法中执行数据表的写入操作。

代码如下:

package com.jiisb.app.controller;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jiisb.app.entity.Article;

@Controller
public class TestController {

    @Autowired
    private SessionFactory sf;

    @ResponseBody
    @RequestMapping("test/index.do")
    public String index(){

        Article art=new Article();
        art.setTitle("技术帮好");
        art.setContent("技术帮好,技术帮好,技术帮是程序员的好领导!");
        Session s = sf.openSession();
        s.save(art);
        s.close();

        return "Hello ,技术帮";
    }

}

log4j配置详解http://www.linuxidc.com/Linux/2014-12/110909.htm

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值