在进行环境搭建的时候我发现国内的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整合内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!
