Spring、SpringMVC、Hibernate详细整合实例,包含所有步骤
Eclipse完整工程如下 Jar包如下
CSDN下载地址:https://download.csdn.net/download/zhutouaizhuwxd/9721062
其中,整个工程主要可以分为四个部分(个人见解,怎么容易理解怎么来)
第一部分:配置文件
1、applicationContentx.xml:配置Spring容器相关内容.
1.1 hibernate.cfg.xml:
1.2 jdbc.properties:
2、Springmvc.xml:配置Springmvc相关内容
3、web.xml:配置整个工程相关内容
第二部分:(映射数据库)
1、实体类Entities
2、*.hbm.xml
第三部分:MVC:
1、控制层Controller(C)
2、业务逻辑层Service、Dao(M)
3、视图层index.jsp(V)
第四部分:JAR包
1、Spring3.X
2、Hibernate3.X
3、连接SqlServer2008数据库:sqljdbc4.jar(其他数据库使用对应的jar包即可)
4、数据库连接池:c3p0
5、commons-logging的jar包
具体代码如下:
第一部分:配置文件
1、applicationContentx.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:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
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-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd "> <!-- 自动扫描与装配Bean -->
<context:component-scan base-package="com.zit" /> <context:annotation-config /> <context:property-placeholder location="classpath:config/jdbc.properties"/> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" >
<!-- 数据连接信息 -->
<property name="jdbcUrl" value="${jdbcUrl}"></property>
<property name="driverClass" value="${driverClass}"></property>
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
</bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" >
<property name="dataSource" ref="dataSource"></property> <!-- 指定hibernate的映射实体类位置 -->
<property name="mappingLocations" value="classpath:com/zit/entities/Student.hbm.xml"></property>
<!-- 指定hibernate的配置文件位置 -->
<property name="configLocation" value="classpath:config/hibernate.cfg.xml"></property> </bean> <!-- 配置一个事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean> <tx:annotation-driven transaction-manager="transactionManager"/> </beans>
1.1 hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!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>
<!-- SQL dialect 方言-->
<property name="dialect">org.hibernate.dialect.SQLServerDialect</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <!-- 映射数据库对应实体类:注解生效方式生效方式 -->
<!-- <mapping class="Entity.Student"/> --> </session-factory> </hibernate-configuration>
1.2 jdbc.properties(根据个人的数据库,更改对应的参数,我的数据库名字是test)
driverClass = com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbcUrl = jdbc:sqlserver://localhost:1433;database=test
user = sa
password = xxxxx
2、Springmvc.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: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-3.0.xsd "> <!-- 注解扫描包,注意换成自己的路径 -->
<context:component-scan base-package="com.zit">
<!-- 只扫描@Controller的部分 -->
<!-- <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> -->
</context:component-scan> <!-- 定义视图解析器 -->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean> </beans>
3、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" 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>SSH</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list> <!-- 加载所有的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/applicationContext.xml</param-value>
</context-param>
<!-- 配置Spring监听 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- 配置SpringMVC -->
<servlet>
<servlet-name>SSH</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:config/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> <servlet-mapping>
<servlet-name>SSH</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> <!-- 加入Hibernate的过滤请求将session打开,不然在Dao层getCurrentSession()时报错 -->
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter> <filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> </web-app>
第二部分:(映射数据库),我的数据库名字是test,里面有张Student表,有id(自增、主键),age,name三个字段
1、实体类Entities:Student.java
package com.zit.entities; import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id; public class Student { private int id; private String name; private int age; public Student(){} public Student(int id,String name,int age){
this.id=id;
this.name=name;
this.age=age;
} public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2、Student.hbm.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping>
<class name="com.zit.entities.Student" table="Student">
<meta attribute="class-description">
This class contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="name" column="name" type="string"/>
<property name="age" column="age" type="int"/>
</class>
</hibernate-mapping>
第三部分:MVC:
1、控制层Controller(C):StudentController.java
package com.zit.controller; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping; import com.zit.entities.Student;
import com.zit.service.StudentService; @Controller
@RequestMapping("/student")
public class StudentController { @Autowired
private StudentService studentService; @RequestMapping("/getAllStudent")
public String getAllStudent(HttpServletRequest request){
String ss = request.getParameter("userName");
List<Student> students = studentService.getAllStudent();
for(Student s : students){
System.out.println(s.getId());
System.out.println(s.getName());
System.out.println(s.getAge());
}
return "index";//返回index.jsp页面 } }
2、业务逻辑层Service、Dao(M)
2.1.1 StudentService.java
package com.zit.service; import java.util.List; import com.zit.entities.Student; public interface StudentService { public List<Student> getAllStudent(); }
2.1.2 StudentServiceImpl.java
package com.zit.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import com.zit.dao.StudentDao;
import com.zit.entities.Student;
import com.zit.service.StudentService; @Service
public class StudentServiceImpl implements StudentService{ @Autowired
private StudentDao studentDao; @Override
public List<Student> getAllStudent() {
return studentDao.getAllStudent();
} }
2.2.1 StudentDao.java
package com.zit.dao; import java.util.List; import com.zit.entities.Student; public interface StudentDao { public List<Student> getAllStudent(); }
2.2.1 StudentDaoImpl.java
package com.zit.dao.impl; import java.util.List; import javax.annotation.Resource; import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional; import com.zit.dao.StudentDao;
import com.zit.entities.Student; @Repository
public class StudentDaoImpl implements StudentDao{ @Resource(name = "sessionFactory")
private SessionFactory sessionFactory; @Override
@Transactional
public List<Student> getAllStudent() {
String hql = "from Student";
//getCurrentSession()比openSession()安全,注意web.xml中的配置,不然会报错
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery(hql); return query.list();
} }
3、视图层index.jsp(V):index.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> <script type="text/javascript">
function addUser(){
var form = document.forms[0];
form.action = "/SSH/student/getAllStudent";
form.method="post";
form.submit();
}
</script> </head>
<body>
<h1>添加用户</h1>
<form action="" name="userForm">
姓名:<input type="text" name="userName">
年龄:<input type="text" name="age">
<input type="button" value="添加" onclick="addUser()">
</form> </body>
</html>
以上配置文件是完整、可行的,建议不要擅自删除,
因为本人搭建期间遇到过几个报错,就是因为擅自删除配置文件,比如:
No Hibernate Session bound to thread, and configuration does not allow creat
等等,在此不一 一列举。
到此,搭建好一个能访问数据库的SSH工程,启动Tomcat,可运行查看效果。
这里的jsp页面只是用来打断点验证能否正常访问数据库的,没有实际意义……
Spring、SpringMVC、Hibernate详细整合实例,包含所有步骤的更多相关文章
- SSH(Spring SpringMVC Hibernate)框架整合
项目说明: 使用SSH(Spring SpringMVC Hibernate)框架整合添加部门功能 项目结构 1.导入依赖jar包 <!--单测--> <dependency&g ...
- Spring+SpringMVC+Hibernate简单整合(转)
SpringMVC又一个漂亮的web框架,他与Struts2并驾齐驱,Struts出世早而占据了一定优势,下面同样做一个简单的应用实例,介绍SpringMVC的基本用法,接下来的博客也将梳理一下Str ...
- Spring+SpringMvc+Hibernate整合记录
Spring+SpringMvc+Hibernate+Maven整合各大配置文件记录 1.Idea新建的Maven架构 2.Maven的对象模型的内容 <project xmlns=" ...
- 笔记48 Spring+SpringMVC+Hibernate整合
搭建Spring+SpringMVC+Hibernate的框架的思路如下: 1.创建Maven项目,按需映入Maven包依赖. 2.搭建Spring:配置Spring对控件层Bean的注入. 3.搭建 ...
- springmvc框架(Spring SpringMVC, Hibernate整合)
直接干货 model 考虑给用户展示什么.关注支撑业务的信息构成.构建成模型. control 调用业务逻辑产生合适的数据以及传递数据给视图用于呈献: view怎样对数据进行布局,以一种优美的方式展示 ...
- 框架篇:Spring+SpringMVC+hibernate整合开发
前言: 最近闲的蛋疼,搭个框架写成博客记录下来,拉通一下之前所学知识,顺带装一下逼. 话不多说,我们直接步入正题. 准备工作: 1/ IntelliJIDEA的安装配置:jdk/tomcat等..(本 ...
- Spring+SpringMVC+MyBatis+easyUI整合优化篇(四)单元测试实例
日常啰嗦 前一篇文章<Spring+SpringMVC+MyBatis+easyUI整合优化篇(三)代码测试>讲了不为和不能两个状态,针对不为,只能自己调整心态了,而对于不能,本文会结合一 ...
- spring+springmvc+hibernate 整合
三大框架反反复复搭了很多次,虽然每次都能搭起来,但是效率不高.最近重新搭了一次,理顺了思路,整理了需要注意的地方,分享出来. 工具:Eclipse(jdk 1.7) spring和hibernate版 ...
- Spring MVC基础知识整理➣Spring+SpringMVC+Hibernate整合操作数据库
概述 Hibernate是一款优秀的ORM框架,能够连接并操作数据库,包括保存和修改数据.Spring MVC是Java的web框架,能够将Hibernate集成进去,完成数据的CRUD.Hibern ...
随机推荐
- lua中产生 1 - n 之间不重复随机数
local function GetRandomNumList(len) local rsList = {} ,len do table.insert(rsList,i) end local num, ...
- python中进程间通讯——文件锁之fcntl模块的使用
python 中给文件加锁——fcntl模块import fcntl 打开一个文件##当前目录下test文件要先存在,如果不存在会报错.或者以写的方式打开f = open('./test')对该文件加 ...
- MySql安装成功后无法远程登录
MySql安装成功之后在服务器能够登录,但是在客户端却不能登录.只需要按照如下操作即可 请使用mysql管理工具,如:SQLyog Enterprise 可能是你的帐号不允许从远程登陆,只能在loca ...
- spring boot: 支持jsp,支持freemarker
spring boot: 支持jsp,支持freemarker 支持jsp: 加入依赖 <!--jsp--> <dependency> <groupId>org.a ...
- .net WinForm 的数据绑定
.net WinForm 的数据绑定相当灵活 http://www.cnblogs.com/ydong/archive/2006/04/22/381847.html 原来只知道 Control 类上的 ...
- 20180226xlVbaGetStockData
Sub LoopGetStockData() Dim StartTime As Variant Dim UsedTime As Variant StartTime = VBA.Timer Cells. ...
- caffe-ssd
1.安装依赖 1 sudo apt-get install libprotobuf-dev libleveldb-dev libsnappy-dev libopencv-dev libhdf5-ser ...
- asyncio创建协程解析——分析廖雪峰的Python教程之创建WEB服务(转)
第一步,搭建开发环境 所需第三方库: aiohttp,异步 Web 开发框架:jinja2,前端模板引擎:aiomysql,异步 mysql 数据库驱动 所需内置库: logging,系统日志:asy ...
- 关于AndroidStudio混淆配置,简单的整理(转)
1.首先需要在app下的build.gradle下配置,true表示编译时会混淆代码<span style="font-size:18px;">buildTypes { ...
- dp 二维乃至多维背包
洛谷P1855 榨取kkksc03 分析:套路是很明显的01背包,但是这时受约束的变量有两个了,这种情况下就该用多维背包了 分析方法一样的,用dp[i][j][k]表示从前i个愿望中挑选总时间和总金钱 ...