Spring5+SpringMvc+Hibernate5整合的实现

 更新时间:2020年06月14日 17:03:34   作者:海Vq2Py  
这篇文章主要介绍了Spring5+SpringMvc+Hibernate5整合的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

在进行环境搭建的时候我发现国内的Spring+SpringMvc+Hibernate整合资料比较少,即使有的话要么就是将所有配置放在一个配置文件,不易于理解结构,要么就是版本太旧,因此这篇文章简单讲解了如何配置相关的开发环境,使用的版本为jdk1.8+spring5+hibernate5

1 分层整合

我们都知道在Spring可以通过<import>标签来将不同的配置文件进行整合的,因此我们就用这个思路来进行整合,我们将全部的配置文件分为dao层,service层和view层,这样整合起来比较方便,也比较容易懂

2 创建项目引入依赖

我们首先创建一个名字为Spring5+SpringMvc+Hibernate5的项目,从原型中找到如下的选项

idea给我们创建的项目默认是不完整的

少了一些文件,我们只需要在src上右键,选择创建对应的文件夹即可


有些低版本的idea可能没有这么只能,你只能手动创建并设置资源和源码目录

创建好了之后我们就可以修改一些pom文件中的配置了,以下的文件可以根据自己的情况进行修改

2.1 引入依赖

spring依赖

<!--spring依赖-->
<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-webmvc</artifactId>
 <version>5.2.0.RELEASE</version>
</dependency>
<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-jdbc</artifactId>
 <version>5.2.0.RELEASE</version>
</dependency>
<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-orm</artifactId>
 <version>5.2.0.RELEASE</version>
</dependency>
<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-test</artifactId>
 <version>5.2.0.RELEASE</version>
 <scope>provided</scope>
</dependency>

hibernate依赖

<!-- hibernate核心依赖-->
<dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-core</artifactId>
 <version>5.2.17.Final</version>
</dependency>
<dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-validator</artifactId>
 <version>5.2.0.Final</version>
</dependency>

数据库和连接池依赖

<!--连接池依赖-->
<dependency>
 <groupId>com.alibaba</groupId>
 <artifactId>druid</artifactId>
 <version>1.1.10</version>
</dependency>

<!-- 数据库依赖 -->
<dependency>
 <groupId>mysql</groupId>
 <artifactId>mysql-connector-java</artifactId>
 <version>8.0.12</version>
</dependency>

引入jsp

<!-- jsp依赖 -->
<dependency>
 <groupId>javax.servlet</groupId>
 <artifactId>javax.servlet-api</artifactId>
 <version>3.1.0</version>
 <scope>provided</scope>
</dependency>
<dependency>
 <groupId>javax.servlet.jsp</groupId>
 <artifactId>jsp-api</artifactId>
 <version>2.1</version>
 <scope>provided</scope>
</dependency>
<dependency>
 <groupId>javax.servlet</groupId>
 <artifactId>jstl</artifactId>
 <version>1.2</version>
</dependency>

jsp其实不是必须,但是你如果需要用到进行不分离的开发,那么该依赖最好还是引入一下

其他的依赖可以根据自己的情况引入

2.2 构建配置修改

在build的时候有可能会出现静态资源没有build的情况,因此可以采用以下方法

<build>
 <resources>
  <resource>
   <directory>src/main/java</directory>
   <includes>
    <include>**/*.xml</include>
    <include>**/*.properties</include>
   </includes>
   <filtering>true</filtering>
  </resource>
  <resource>
   <directory>src/main/resources</directory>
   <includes>
    <include>**/*.xml</include>
    <include>**/*.properties</include>
   </includes>
   <filtering>true</filtering>
  </resource>
 </resources>
 .......
</build>

3 准备数据库

我们在这里准备一个名字为hibernate的数据库,请自行创建,至于数据库表我们则不需要创建

4 配置dao层

我们首先在resources下准备一个db-mysql.properties文件,内容如下

jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/hibernate?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456

请根据自己的数据库版本和配置进行书写,当然这一步不是必须的,但是为了方便找到对应配置项,你可准备这个文件

好了我们可以开始进行spring的配置了,在resources文件夹下创建一个spring-dao,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:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop.xsd
  http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx.xsd">

 <!-- 开启注解扫描-->
 <context:annotation-config></context:annotation-config>
 <context:component-scan base-package="com.fzu.pojo"></context:component-scan>

 <!-- 加载配置文件-->
 <context:property-placeholder location="classpath:db-mysql.properties"></context:property-placeholder>
 <!-- 配置数据源-->
 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
   destroy-method="close" lazy-init="false">
  <property name="driverClassName" value="${jdbc.driverClassName}" />
  <property name="url" value="${jdbc.url}" />
  <property name="username" value="${jdbc.username}" />
  <property name="password" value="${jdbc.password}" />

  <property name="initialSize" value="1" />
  <property name="maxActive" value="50" />
  <property name="maxWait" value="30000" />
  <property name="filters" value="stat,wall" />
  <property name="timeBetweenEvictionRunsMillis" value="3000" />
  <property name="minEvictableIdleTimeMillis" value="300000" />
  <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="20" />
 </bean>

 <!--配置sessionFactory-->
 <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
  <property name="dataSource" ref="dataSource"></property>
  <property name="packagesToScan" value="com.fzu.pojo"></property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.hbm2ddl.auto">update</prop>
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQL55Dialect</prop>
    <prop key="hibernate.show_sql">true</prop>
    <prop key="hibernate.format_sql">true</prop>
   </props>
  </property>
 </bean>
 <!-- 配置事务管理-->
 <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory"></property>
 </bean>
 <!-- 开启注解事务管理 -->
 <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>

 <!--配置hibernatetemplate-->
 <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
  <property name="sessionFactory" ref="sessionFactory"></property>
 </bean>
 
</beans>

请根据自己的情况创建对应的包和选择相应的属性例如数据库方言,我这里是选择了com.fzu.pojo下存放实体类,我创建了一个Student实体类,其中关于hibernate注解的内容我们不赘述

package com.fzu.pojo;

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

@Entity
@Table
public class Student {


 @Id
 private Long studentid;
 private String name;
 private Integer age;
 // 这里请不要用desc,这个是mysql保留字
 private String description;

 @Override
 public String toString() {
  return "Student{" +
    "studentid=" + studentid +
    ", name='" + name + '\'' +
    ", age=" + age +
    ", description='" + description + '\'' +
    '}';
 }

 public Long getStudentid() {
  return studentid;
 }

 public void setStudentid(Long studentid) {
  this.studentid = studentid;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public Integer getAge() {
  return age;
 }

 public void setAge(Integer age) {
  this.age = age;
 }

 public String getDescription() {
  return description;
 }

 public void setDescription(String description) {
  this.description = description;
 }
}

最后在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:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop.xsd
  http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx.xsd">

 <!-- 开启注解扫描-->
 <context:component-scan base-package="com.fzu">
  <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
 </context:component-scan>
 <context:annotation-config></context:annotation-config>
 <import resource="classpath:spring-dao.xml"/>
 <import resource="classpath:spring-mvc.xml"/>
</beans>

由于这里我们service层的内容比较少我们就不单独创建一个配置文件了

5 配置mvc层

创建spring-mvc.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:aop="http://www.springframework.org/schema/aop"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context.xsd
  http://www.springframework.org/schema/aop
  http://www.springframework.org/schema/aop/spring-aop.xsd
  http://www.springframework.org/schema/tx
  http://www.springframework.org/schema/tx/spring-tx.xsd
  http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">

 <!--注解驱动-->
 <mvc:annotation-driven></mvc:annotation-driven>

 <!--过滤静态资源 -->
 <mvc:default-servlet-handler></mvc:default-servlet-handler>

 <!--扫描controller-->
 <context:component-scan base-package="com.fzu.controller"></context:component-scan>

 <!--视图解析器-->
 <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/jsp/"></property>
  <property name="suffix" value=".jsp"></property>
 </bean>
</beans>

其中视图解析器路径和扫描的包可以自行确定,不要忘记在applicationContext.xml中引入

6 配置web.xml

我们需要在web.xml中配置spring容器,视图servlet和编码servlet

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
      http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
   version="4.0">

 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
  <welcome-file>index.html</welcome-file>
 </welcome-file-list>

 <!-- 配置请求分发器 -->
 <servlet>
  <servlet-name>dispatcherServlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <init-param>
   <param-name>contextConfigLocation</param-name>
   <param-value>classpath:spring-mvc.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>dispatcherServlet</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping>

 <!-- 配置字符过滤器 -->
 <filter>
  <filter-name>encodingFilter</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <init-param>
   <param-name>encoding</param-name>
   <param-value>UTF-8</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>encodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

 <!-- 监听spring容器自动启动 -->
 <context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>classpath:applicationContext.xml</param-value>
 </context-param>
 <listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>

 <!-- 配置session过期时间-->
 <session-config>
  <session-timeout>15</session-timeout>
 </session-config>
</web-app>

在创建完相应的类之后,请不要忘记配置tomcat服务器,再启动之后我们就可以看到相应的表创建了

7 总结

我们首先看一下最后的文件结构

可以看到我们的整个配置过程是模块化的,从dao层往上,每一层都可以单独拆装,除此之外我们项进行其他配置也是很简单的,例如如果我们想要新增一个redis配置

我们可以按照如下步骤

  • 引入相关依赖
  • 创建db-redis.properties配置文件
  • 创建spring-redis.xml配置文件并进行配置
  • 在applicationContext中引入即可

可以看到整个过程逻辑很清晰

到此这篇关于Spring5+SpringMvc+Hibernate5整合的实现的文章就介绍到这了,更多相关Spring5+SpringMvc+Hibernate5整合内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 五分钟解锁springboot admin监控新技巧

    五分钟解锁springboot admin监控新技巧

    本文不会讲如何搭建企业的运维监控系统,有兴趣的可以去找找成熟的比如Zabbix、Prometheus,甚至比较简单的Wgcloud都能满足一定的需求,不在此赘述。本文讲解如何使用Springboot admin对spring boot项目进行应用监控,感兴趣的朋友一起看看吧
    2021-06-06
  • Java servlet后端开发超详细教程

    Java servlet后端开发超详细教程

    Servlet指在服务器端执行的一段Java代码,可以接收用户的请求和返回给用户响应结果,下面这篇文章主要给大家介绍了关于Java.servlet生命周期的相关资料,需要的朋友可以参考下
    2023-02-02
  • Java设计模式系列之深入浅出单例模式

    Java设计模式系列之深入浅出单例模式

    设计模式是在大量的实践中总结和理论之后优选的代码结构,编程风格,以及解决问题的思考方式,下面这篇文章主要给大家介绍了关于Java设计模式系列之深入浅出单例模式的相关资料,需要的朋友可以参考下
    2021-09-09
  • Java中的拦截器、过滤器、监听器用法详解

    Java中的拦截器、过滤器、监听器用法详解

    这篇文章主要介绍了Java中的拦截器、过滤器、监听器用法,详细分析了Java拦截器、过滤器、监听器的功能、使用方法及相关注意事项,需要的朋友可以参考下
    2017-05-05
  • spring中实现容器加载完成后再执行自己的方法

    spring中实现容器加载完成后再执行自己的方法

    这篇文章主要介绍了spring中实现容器加载完成后再执行自己的方法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-02-02
  • java设计模式之中介者模式

    java设计模式之中介者模式

    这篇文章主要为大家详细介绍了java设计模式之中介者模式,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-08-08
  • 10个Java文件操作必备技巧分享

    10个Java文件操作必备技巧分享

    在我们日常的开发中,文件操作是一个非常重要的主题。文件读写、文件复制、任意位置读写、缓存等技巧都是我们必须要掌握的。本文为大家整理了10个实用的文件操作技巧,希望对大家有所帮助
    2023-04-04
  • Spring cloud踩坑记录之使用feignclient远程调用服务404的方法

    Spring cloud踩坑记录之使用feignclient远程调用服务404的方法

    这篇文章主要给大家介绍了关于Spring cloud踩坑记录之使用feignclient远程调用服务404的相关资料,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-11-11
  • Java中byte、byte数组与int、long的转换详解

    Java中byte、byte数组与int、long的转换详解

    这篇文章分别给大家介绍了Java中byte和int之间的转换、Java中 byte数组和int之间的转换、Java中byte数组和long之间的转换以及整理了整体工具类的源码,需要的朋友可以参考借鉴,下面来一起看看吧。
    2017-02-02
  • java持久层框架mybatis防止sql注入的方法

    java持久层框架mybatis防止sql注入的方法

    下面小编就为大家带来一篇java持久层框架mybatis防止sql注入的方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2016-10-10

最新评论