首页 > 代码库 > Spring MVC基础知识整理?Spring+SpringMVC+Hibernate整合操作数据库
Spring MVC基础知识整理?Spring+SpringMVC+Hibernate整合操作数据库
概述
Hibernate是一款优秀的ORM框架,能够连接并操作数据库,包括保存和修改数据。Spring MVC是Java的web框架,能够将Hibernate集成进去,完成数据的CRUD。Hibernate使用方便,配置响应的XML文件即可。由于spring3.x,基于asm的某些特征,而这些asm还没有用jdk8编译,所以采用Spring 3+JDK8就会报错,提示错误信息( java.lang.IllegalArgumentException),具体解决方案有:1、Spring 3+JDK7及以下版本 2、Spring 4+JDK8及以上版本;具体可参考大牛地址
Spring+SpringMVC+Hibernate操作数据
这里采用Spring 4+Hibernate4进行代码整合,Spring4主要处理WEB请求,Hibernate4进行数据的操作;
引用类包
所需要的类包文件清单如下图,如需下载,可通过下面Demo下载,类包位于WEBINF-->Lib目录下
添加配置文件
WEB.XML文件,配置内容如下
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>SpringMVC</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 配置Spring --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/spring-*.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
<!-- 配置SpringMVC --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:config/spring-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springMVC</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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 控制Session的开关 --> <filter> <filter-name>openSession</filter-name> <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class> </filter> <filter-mapping> <filter-name>openSession</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
在src目录下,添加文件夹config/spring-hibernate.xml(存储Hibernate配置信息,包括数据库连接字符串的读取)、config/spring-servlet.xml(配置Spring-MVC的依赖注入)、config.hibernate/hiernate.cfg.xml(配置Hibernate的依赖注入实体对象)、config.spring/spring-user.xml(配置Spring DAO和Service配置)、prop/jdbc.properities(配置数据库连接信息);
XML配置如下
spring-hibernate.xml内容
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.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-4.0.xsd"> <!-- 引入property配置文件 --> <context:property-placeholder location="classpath:prop/jdbc.properties"/> <!-- 配置数据源 --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value=http://www.mamicode.com/"${jdbc.mysql.driverClassName}" /> <property name="url" value=http://www.mamicode.com/"${jdbc.mysql.url}" /> <property name="username" value=http://www.mamicode.com/"${jdbc.mysql.username}" /> <property name="password" value=http://www.mamicode.com/"${jdbc.mysql.password}" /> </bean> <!-- 配置hibernate SessionFactory--> <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${jdbc.mysql.dialect}</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.show_sql">true</prop> <prop key="hiberante.format_sql">true</prop> </props> </property> <property name="configLocations"> <list> <value> classpath*:config/hibernate/hibernate.cfg.xml </value> </list> </property> </bean> <!-- 事务管理器 --> <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <!-- 事务代理类 --> <bean id="transactionBese" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" lazy-init="true" abstract="true"> <property name="transactionManager" ref="transactionManager"></property> <property name="transactionAttributes"> <props> <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="del*">PROPAGATION_REQUIRED,-Exception</prop> <prop key="get*">PROPAGATION_NEVER</prop> </props> </property> </bean></beans>
spring-servlet.xml内容
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.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-3.0.xsd"> <!-- 注解扫描的包 --> <context:component-scan base-package="com.jialin" /> <!-- 开启注解方案1 --> <!-- 注解方法处理 --> <!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> --> <!-- 注解类映射处理 --> <!-- <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean> --> <!-- 开启注解方案2 --> <mvc:annotation-driven /> <!-- 静态资源访问,方案1 --> <mvc:resources location="/img/" mapping="/img/**" /> <mvc:resources location="/js/" mapping="/js/**" /> <!-- 静态资源访问,方案2 --> <!-- <mvc:default-servlet-handler/> --> <!-- 视图解释类 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value=http://www.mamicode.com/"/"></property> <!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑 --> <property name="suffix" value=http://www.mamicode.com/".jsp"></property> </bean> <!-- 上传文件bean --> <!-- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value=http://www.mamicode.com/"utf-8" /> <property name="maxUploadSize" value="10485760000" /> <property name="maxInMemorySize" value=http://www.mamicode.com/"40960" /> </bean> --></beans>
hiernate.cfg.xml内容
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"><hibernate-configuration> <session-factory> <!-- 引入需要映射的类 --> <mapping class="com.jialin.entity.User"/> </session-factory></hibernate-configuration>
spring-user.xml内容
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [<!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">]><beans> <!-- Spring Bean --> <bean id="userDao" class="com.jialin.dao.UserDao"> <property name="sessionFactory" ref="sessionFactory"></property> </bean> <bean id="userManagerBase" class="com.jialin.service.UserManager"> <property name="userDao" ref="userDao"></property> </bean> <!-- parent为transactionBese,表示支持事务 --> <bean id="userManager" parent="transactionBese"> <property name="target" ref="userManagerBase"></property> </bean> </beans>
jdbc.properities内容
# JDBC # 设置连接池连接时的数量 jdbc.initialSize=1 jdbc.filters=stat # 连接池中存在的最小连接数目。连接池中连接数目可以变很少,如果使用了maxAge属性,有些空闲的连接会被关闭因为离它最近一次连接的时间过去太久了。
#但是,我们看到的打开的连接不会少于minIdle。 jdbc.minIdle=1 # 连接数据库的最大连接数。这个属性用来限制连接池中能够打开连接的数量,可以方便数据库做连接容量规划。 jdbc.maxActive=99 jdbc.maxWait=1000 jdbc.minEvictableIdleTimeMillis=300000 jdbc.poolPreparedStatements=true jdbc.maxPoolPreparedStatementPerConnectionSize=50 jdbc.timeBetweenEvictionRunsMillis=60000 jdbc.validationQuery=select 1 from dual jdbc.removeAbandonedTimeout=150 jdbc.logAbandoned=true jdbc.removeAbandoned=true jdbc.testOnBorrow=false jdbc.testOnReturn=false # MYSQL 数据库连接方式 jdbc.mysql.driverClassName=com.mysql.jdbc.Driverjdbc.mysql.url=jdbc:mysql://192.168.1.102:3306/dbidb?characterEncoding=UTF-8jdbc.mysql.username=rootjdbc.mysql.password=rootjdbc.mysql.dialect=org.hibernate.dialect.MySQLDialect #HIBERNATE jdbc.show_sql=false jdbc.format_sql=false
编写代码
数据库操作服务层代码
添加User实体
import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.Table;import org.hibernate.annotations.GenericGenerator;@Entity@Table(name="Users")public class User { @Id @GeneratedValue(generator="id") @GenericGenerator(name = "id",strategy="identity") private Integer id; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } @Column(name="userName") private String userName; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } @Column(name="age") private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
添加DAO文件
package com.jialin.dao;import com.jialin.entity.User;public interface IUserDao { void addUser(User user) throws Exception; }
实现IUserDao接口,某些属性要实现get和set属性,且要和配置文件hiernate.cfg.xml对应,否则依赖注入失败
package com.jialin.dao;import org.hibernate.SessionFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Repository;import com.jialin.entity.User;@Repositorypublic class UserDao implements IUserDao { @Autowired private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Override public void addUser(User user) throws Exception { System.out.println("11111111111111111"+user.getUserName()); sessionFactory.getCurrentSession().save(user); } }
添加服务接口
package com.jialin.service;import com.jialin.entity.User;public interface IUserManager { //添加用户 void addUser(User user) throws Exception; }
实现服务接口
package com.jialin.service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.jialin.dao.UserDao;import com.jialin.entity.User;@Service("userService") public class UserManager implements IUserManager { @Autowired private UserDao userDao; public UserDao getUserDao() { return userDao; } public void setUserDao(UserDao userDao) { this.userDao = userDao; } @Override public void addUser(User user) throws Exception { // TODO Auto-generated method stub userDao.addUser(user); }}
WEB层代码
添加Controller类
package com.jialin.controller;import javax.servlet.http.HttpServletRequest;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import com.jialin.entity.User;import com.jialin.service.UserManager;@Controllerpublic class UserController { @Autowired private UserManager userService; //添加用户 @RequestMapping(value=http://www.mamicode.com/"/user/addUser",method=RequestMethod.POST) public String addUser(User user,HttpServletRequest request) throws Exception{ System.out.println("用户名:======"+user.getUserName()); userService.addUser(user); return "success"; } @RequestMapping(value="/user/addUser",method=RequestMethod.GET) public String addUserIndex(Model model) throws Exception{ model.addAttribute("", new User()); return "UserAdd"; } }
添加UserAdd.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body> <form action="" method="post"> <h3>添加用户信息</h3> 姓名:<input type="text" name="userName" id="userName" value="" /> 年龄:<input type="text" name="age" id="age" value="" /> <input type="submit" value=http://www.mamicode.com/"提交" /> </form></body></html>
添加success.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body>操作成功</body></html>
至此,Hibbernate配置完成,这里仅演示添加操作!
源码下载
Spring MVC基础知识整理?Spring+SpringMVC+Hibernate整合操作数据库