spring+springmvc+hibernate 整合
本文内容纲要:
-1.新建一个mavenweb项目。(没用过maven的可以i先去了解一下)
-2.pom文件,导入jar包
-3.配置文件
-4.spring-mvc和spring整合
-5.spring和hibernate整合
-6.总结
三大框架反反复复搭了很多次,虽然每次都能搭起来,但是效率不高。最近重新搭了一次,理顺了思路,整理了需要注意的地方,分享出来。
工具:Eclipse(jdk1.7)spring和hibernate版本均为4.0以上
推荐使用maven构建项目,相比自己手动导入jar包要方便很多。
1.新建一个mavenweb项目。(没用过maven的可以i先去了解一下)
注意点:使用Eclipse创建的maven工程文件结构可能不太正确,需要自己手动创建文件夹。
正确的文件结构:
-src
---main
------java(class文件)
------resources(配置文件)
------webapp(web文件)
---test(测试文件)
------java
------resources
2.pom文件,导入jar包
导入jar包也是框架整合中比较麻烦的点,常常会导入太多不相关的包,但由于不熟悉又不敢删掉,于是jar
包越导越多,到最后框架是搭起来,但jar包却导了十几二十个。
注意点:这里建议的做法是当你不熟悉框架需要导入什么jar包时,可以先导入核心包,然后当运行项目时提示NotFoundClass时,再根据错误提示添加相关的依赖,这样就不会导入多余的jar包。
推荐可以到该网站上去搜索你需要的依赖:https://mvnrepository.com/
pom文件:
1<projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
2xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/maven-v4_0_0.xsd">
3<modelVersion>4.0.0</modelVersion>
4<groupId>hcoding</groupId>
5<artifactId>MyWebDemo</artifactId>
6<packaging>war</packaging>
7<version>0.0.1-SNAPSHOT</version>
8<name>MyWebDemoMavenWebapp</name>
9<url>http://maven.apache.org</url>
10
11<dependencies>
12<dependency>
13<groupId>junit</groupId>
14<artifactId>junit</artifactId>
15<version>3.8.1</version>
16<scope>test</scope>
17</dependency>
18
19<!--springstart-->
20<dependency>
21<groupId>org.springframework</groupId>
22<artifactId>spring-context</artifactId>
23<version>4.3.9.RELEASE</version>
24</dependency>
25<dependency>
26<groupId>org.springframework</groupId>
27<artifactId>spring-core</artifactId>
28<version>4.3.9.RELEASE</version>
29</dependency>
30<dependency>
31<groupId>org.springframework</groupId>
32<artifactId>spring-beans</artifactId>
33<version>4.3.9.RELEASE</version>
34</dependency>
35<dependency>
36<groupId>org.springframework</groupId>
37<artifactId>spring-web</artifactId>
38<version>4.3.9.RELEASE</version>
39</dependency>
40<dependency>
41<groupId>org.springframework</groupId>
42<artifactId>spring-aspects</artifactId>
43<version>4.3.9.RELEASE</version>
44</dependency>
45<dependency>
46<groupId>org.springframework</groupId>
47<artifactId>spring-orm</artifactId>
48<version>4.3.9.RELEASE</version>
49</dependency>
50<!--springend-->
51
52<!--springmvcstart-->
53<dependency>
54<groupId>org.springframework</groupId>
55<artifactId>spring-webmvc</artifactId>
56<version>4.3.9.RELEASE</version>
57</dependency>
58<!--springmvcend-->
59
60<!--logingstart-->
61<dependency>
62<groupId>org.slf4j</groupId>
63<artifactId>slf4j-api</artifactId>
64<version>1.7.6</version>
65</dependency>
66<!--logingend-->
67
68<dependency>
69<groupId>aspectj</groupId>
70<artifactId>aspectjrt</artifactId>
71<version>1.5.3</version>
72</dependency>
73<dependency>
74<groupId>org.aspectj</groupId>
75<artifactId>aspectjtools</artifactId>
76<version>1.8.7</version>
77</dependency>
78<dependency>
79<groupId>javax.servlet</groupId>
80<artifactId>jstl</artifactId>
81<version>1.2</version>
82<scope>runtime</scope>
83</dependency>
84<dependency>
85<groupId>javax.annotation</groupId>
86<artifactId>javax.annotation-api</artifactId>
87<version>1.2</version>
88</dependency>
89<dependency>
90<groupId>javax.servlet</groupId>
91<artifactId>servlet-api</artifactId>
92<version>2.5</version>
93</dependency>
94
95<!--hibernatestart-->
96<dependency>
97<groupId>org.hibernate</groupId>
98<artifactId>hibernate-core</artifactId>
99<version>4.2.3.Final</version>
100</dependency>
101<!--hibernateend-->
102
103<!--c3p0start-->
104<dependency>
105<groupId>c3p0</groupId>
106<artifactId>c3p0</artifactId>
107<version>0.9.1.2</version>
108</dependency>
109<!--c3p0end-->
110
111<!--mysqlstart-->
112<dependency>
113<groupId>mysql</groupId>
114<artifactId>mysql-connector-java</artifactId>
115<version>5.1.35</version>
116</dependency>
117<!--mysqlend-->
118</dependencies>
119<build>
120<finalName>MyWebDemo</finalName>
121</build>
122</project>
其中,注释块
比如,我的项目中使用的是mysql数据库和c3p0数据源,所以引入MySQL和c3p0的依赖,如果你使用的是其他数据库和数据源就需要做相应的修改。
pom文件中为注释的部分则是在项目运行时提示的jar包缺失引入的依赖,有的是spring框架依赖的包,有的则是servlet或者jsp依赖的,如果第一次搭建时不熟悉可以先不导入,等报错时再引入依赖,这样也可以加深理解。
3.配置文件
这是框架整合最重要的部分。配置文件除了web.xml之外都放在main/resources文件夹中,当然你也可以放在其他自己新建的文件夹下,不过配置文件地址要做相应的修改,这个等会详细说。
配置文件的配置,很多框架整合的教程都不太一样的,这里给出我自己的配置方法和做法。
配置文件主要分为四个:web.xm,beans.xml,spring-mvc.xml,datasource.xml。
配置步骤分为两步,spring-mvc和spring的整合,hibernate和spring的整合,最后再运行项目。(这也是效率比较高的做法,分开整合,这样即使运行项目有报错也比较好找,而且分部整合不容易乱)
接下来就开始具体配置。
4.spring-mvc和spring整合
这是spring-mvc.xml配置文件:
1<beansxmlns="http://www.springframework.org/schema/beans"
2xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3xmlns:context="http://www.springframework.org/schema/context"
4xmlns:mvc="http://www.springframework.org/schema/mvc"
5xsi:schemaLocation="http://www.springframework.org/schema/beans
6http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
7http://www.springframework.org/schema/context
8http://www.springframework.org/schema/context/spring-context-4.1.xsd
9http://www.springframework.org/schema/mvc
10http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
11
12<mvc:annotation-driven/>
13
14<context:component-scanbase-package="com.hcoding.demo">
15<context:include-filtertype="annotation"
16expression="org.springframework.stereotype.Controller"/>
17<!--排除@service注解的类-->
18<context:exclude-filtertype="annotation"
19expression="org.springframework.stereotype.Service"/>
20</context:component-scan>
21
22<!--对模型视图名称的解析,在请求时模型视图名称添加前后缀-->
23<beanid="viewResolver"class="org.springframework.web.servlet.view.InternalResourceViewResolver">
24<propertyname="viewClass"value="org.springframework.web.servlet.view.JstlView"/>
25<propertyname="prefix"value="demo/"/><!--前缀-->
26<propertyname="suffix"value=".jsp"/><!--后缀-->
27</bean>
28
29<!--对静态资源的映射-->
30<mvc:resourcesmapping="/js/**"location="/resources/js/"/>
31<mvc:resourcesmapping="/css/**"location="/resources/css/"/>
32<mvc:resourcesmapping="/img/**"location="/resources/img/"/>
33
34</beans>
这是spring-mvc基本的配置,主要是对请求和静态资源映射的配置。
注意点:1.需要特别注意的是扫描包时要排除service层的类,不然在整合hibernate后,项目运行时会报错。
具体原因看一下这个网址:http://blog.csdn.net/xiaobao5214/article/details/52042041
2.然后就是如果你的包名和结构不一样的,那么扫描的包地址也要记得更换。
然后是web.xml配置文件:
1<!DOCTYPEweb-appPUBLIC
2"-//SunMicrosystems,Inc.//DTDWebApplication2.3//EN"
3"http://java.sun.com/dtd/web-app_2_3.dtd">
4
5<web-app>
6<display-name>MyWebDemo</display-name>
7
8<!--统一编码解决中文乱码问题-->
9<filter>
10<filter-name>charsetEncoding</filter-name>
11<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
12<init-param>
13<param-name>encoding</param-name>
14<param-value>UTF-8</param-value>
15</init-param>
16<init-param>
17<param-name>forceEncoding</param-name>
18<param-value>true</param-value>
19</init-param>
20</filter>
21<filter-mapping>
22<filter-name>charsetEncoding</filter-name>
23<url-pattern>/*</url-pattern>
24</filter-mapping>
25
26<!--springMVC配置-->
27<servlet>
28<servlet-name>spring</servlet-name>
29<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
30<init-param>
31<param-name>contextConfigLocation</param-name>
32<!--此处指向的的是SpringMVC的配置文件如果配置文件地址和名称不一样需要更改-->
33<param-value>classpath:spring-mvc.xml</param-value>
34</init-param>
35<!--配置容器在启动的时候就加载这个servlet并实例化-->
36<load-on-startup>1</load-on-startup>
37</servlet>
38
39<servlet-mapping>
40<servlet-name>spring</servlet-name>
41<url-pattern>/</url-pattern>
42</servlet-mapping>
43<!--springMVCconfigend-->
44
45</web-app>
将spring-mvc配置文件加到web.xml中,当服务器启动项目时,才会加载springmvc。配置完成后写个例子测试一下。
此时的项目结构:
-src
---main
------java(class文件)
----------com.hcoding.controller
----------com.hcoding.service
----------com.hcoding.dao
----------com.hcoding.model
------resources(配置文件)
----------spring-mvc.xml
------webapp(web文件)
----------demo(jsp文件)
----------resources(静态资源文件:css,js,img)
----------WEB-INF(web相关配置文件)
先在controller包中创建DemoController,class:
1packagecom.hcoding.demo.controller;
2
3importjava.util.HashMap;
4importjava.util.Map;
5importjava.util.concurrent.TimeUnit;
6
7importjavax.annotation.Resource;
8importjavax.servlet.http.HttpServletRequest;
9
10importorg.springframework.stereotype.Controller;
11importorg.springframework.web.bind.annotation.RequestMapping;
12importorg.springframework.web.servlet.ModelAndView;
13
14importcom.alibaba.fastjson.JSON;
15importcom.hcoding.demo.model.People;
16importcom.hcoding.demo.service.DemoService;
17
18@Controller
19publicclassDemoController{
20
21@RequestMapping("/test")
22publicStringtest(){
23return"test";
24}
25}
然后在demo文件夹中创建demo.jsp:
1<%@pagelanguage="java"contentType="text/html;UTF-8"
2pageEncoding="UTF-8"%>
3<!DOCTYPEhtmlPUBLIC"-//W3C//DTDHTML4.01Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
4<html>
5<head>
6<metahttp-equiv="Content-Type"content="text/html;charset=utf-8">
7<title>Inserttitlehere</title>
8</head>
9<body>
10<p>这是测试页面。</p>
11</html>
启动项目,在浏览器中输入地址:http://localhost:8080/(项目名)/test。成功可以看到页面。
5.spring和hibernate整合
datasource.xml配置文件:
1<?xmlversion="1.0"encoding="UTF-8"?>
2<beansxmlns="http://www.springframework.org/schema/beans"
3xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4xmlns:jee="http://www.springframework.org/schema/jee"
5xmlns:tx="http://www.springframework.org/schema/tx"
6xmlns:context="http://www.springframework.org/schema/context"
7xmlns:aop="http://www.springframework.org/schema/aop"
8xsi:schemaLocation="
9http://www.springframework.org/schema/aop
10http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
11http://www.springframework.org/schema/beans
12http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
13http://www.springframework.org/schema/tx
14http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
15http://www.springframework.org/schema/jee
16http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
17http://www.springframework.org/schema/context
18http://www.springframework.org/schema/context/spring-context-3.2.xsd">
19
20<!--配置数据源这里是使用的是c3p0连接池-->
21<beanid="dataSource"class="com.mchange.v2.c3p0.ComboPooledDataSource"destroy-method="close">
22<propertyname="driverClass"value="${jdbc.driver}"/><!--数据库连接驱动-->
23<propertyname="jdbcUrl"value="${jdbc.url}"/><!--数据库地址-->
24<propertyname="user"value="${jdbc.username}"/><!--用户名-->
25<propertyname="password"value="${jdbc.password}"/><!--密码-->
26<propertyname="maxPoolSize"value="40"/><!--最大连接数-->
27<propertyname="minPoolSize"value="1"/><!--最小连接数-->
28<propertyname="initialPoolSize"value="10"/><!--初始化连接池内的数据库连接-->
29<propertyname="maxIdleTime"value="20"/><!--最大空闲时间-->
30</bean>
31
32<!--配置session工厂-->
33<beanid="sessionFactory"class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
34<propertyname="dataSource"ref="dataSource"/>
35<propertyname="packagesToScan"value="com.hcoding.demo"/>
36<propertyname="hibernateProperties">
37<props>
38<propkey="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop><!--hibernate根据实体自动生成数据库表-->
39<propkey="hibernate.dialect">${hibernate.dialect}</prop><!--指定数据库方言-->
40<propkey="hibernate.show_sql">${hibernate.show_sql}</prop><!--在控制台显示执行的数据库操作语句-->
41<propkey="hibernate.format_sql">${hibernate.format_sql}</prop><!--在控制台显示执行的数据哭操作语句(格式)-->
42</props>
43</property>
44</bean>
45
46<!--事务配置声明式事务-->
47<beanid="transactionManager"
48class="org.springframework.orm.hibernate4.HibernateTransactionManager">
49<propertyname="sessionFactory"ref="sessionFactory"/>
50</bean>
51<!--使用annotation定义事务-->
52<tx:annotation-driventransaction-manager="transactionManager"/>
53</beans>
datasource.properties文件:
1#databaseconnectionconfig
2jdbc.driver=com.mysql.jdbc.Driver
3jdbc.url=jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf-8
4jdbc.username=root
5jdbc.password=123456
6
7#hibernateconfig
8hibernate.dialect=org.hibernate.dialect.MySQLDialect
9hibernate.show_sql=true
10hibernate.format_sql=true
11hibernate.hbm2ddl.auto=update
beans.xml文件:
1<?xmlversion="1.0"encoding="UTF-8"?>
2<beansxmlns="http://www.springframework.org/schema/beans"
3xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:context="http://www.springframework.org/schema/context"
4xmlns:p="http://www.springframework.org/schema/p"xmlns:cache="http://www.springframework.org/schema/cache"
5xsi:schemaLocation="
6http://www.springframework.org/schema/beans
7http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
8http://www.springframework.org/schema/context
9http://www.springframework.org/schema/context/spring-context-3.0.xsd
10http://www.springframework.org/schema/cache
11http://www.springframework.org/schema/cache/spring-cache-3.1.xsd">
12
13<!--注解-->
14<context:annotation-config/>
15<!--扫描-->
16<context:component-scanbase-package="com.hcoding.demo">
17<context:exclude-filtertype="annotation"
18expression="org.springframework.stereotype.Controller"/>
19</context:component-scan>
20
21<!--导入多个Properties配置文件-->
22<beanid="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
23<propertyname="locations">
24<list>
25<!--要是有多个配置文件,只需在这里继续添加即可-->
26<value>classpath:datasource.properties</value>
27</list>
28</property>
29</bean>
30
31<!--加载数据源组件-->
32<importresource="classpath:datasource.xml"/>
33
34</beans>
注意点:在xml导入properties文件是比较常见,将一些相关的配置数据写到properyties文件中也是常用的方法,利于修改。
常见的另一种导入propertise的方法:在<context:property-placeholderlocation="classpath:/datasource.properties"/>。这种方法spring默认值只导入一个properties,
当有多个properties文件需要导入时,则需要使用另一种方法:
1<!--导入多个Properties配置文件-->
2<beanid="propertyConfigurer"class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
3<propertyname="locations">
4<list>
5<!--要是有多个配置文件,只需在这里继续添加即可-->
6<value>classpath:datasource.properties</value>
7<value>classpath:redis.properties</value>
8</list>
9</property>
10</bean>
个人比较推荐这种,随着项目扩展,需要导入的配置增多,肯定不止一个properties文件,这种方法更通用。
注意点:datasource.properties文件中的数据库地址,用户和密码根据自己的情况做相应的修改。
修改之前的web.xml文件:
1<!DOCTYPEweb-appPUBLIC
2"-//SunMicrosystems,Inc.//DTDWebApplication2.3//EN"
3"http://java.sun.com/dtd/web-app_2_3.dtd">
4
5<web-app>
6<display-name>MyWebDemo</display-name>
7
8<!--统一编码解决中文乱码问题-->
9<filter>
10<filter-name>charsetEncoding</filter-name>
11<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
12<init-param>
13<param-name>encoding</param-name>
14<param-value>UTF-8</param-value>
15</init-param>
16<init-param>
17<param-name>forceEncoding</param-name>
18<param-value>true</param-value>
19</init-param>
20</filter>
21<filter-mapping>
22<filter-name>charsetEncoding</filter-name>
23<url-pattern>/*</url-pattern>
24</filter-mapping>
25
26<!--springMVC配置-->
27<servlet>
28<servlet-name>spring</servlet-name>
29<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
30<init-param>
31<param-name>contextConfigLocation</param-name>
32<!--此处指向的的是SpringMVC的配置文件-->
33<param-value>classpath:spring-mvc.xml</param-value>
34</init-param>
35<!--配置容器在启动的时候就加载这个servlet并实例化-->
36<load-on-startup>1</load-on-startup>
37</servlet>
38
39<servlet-mapping>
40<servlet-name>spring</servlet-name>
41<url-pattern>/</url-pattern>
42</servlet-mapping>
43<!--springMVCconfigend-->
44
45<!--加载spring配置文件-->
46<context-param>
47<param-name>contextConfigLocation</param-name>
48<param-value>classpath:beans.xml</param-value>
49</context-param>
50<!--listener-->
51<listener>
52<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
53</listener>
54
55</web-app>
这就是spring整合hibernate所需要配置的四个文件。文件的加载顺序和包含关系:web.xml→bans.xml→datasource.xml→datasource.properties
注意点:如果你的配置文件名称和存放位置不同,那么你也需要相应的修改。
注意点:一定要记得配置事务,否则操作数据库时项目可能不会报错,但数据库中的数据将不会更新(删除或者修改)。具体可以自行百度事务相关的知识。
配置完成后写个例子测试一下。
在model包中创建People.class:
1packagecom.hcoding.demo.model;
2
3importjava.util.Set;
4
5importjavax.persistence.Column;
6importjavax.persistence.Entity;
7importjavax.persistence.Id;
8importjavax.persistence.Table;
9importjavax.persistence.Transient;
10
11@Entity
12@Table(name="people")
13publicclassPeople{
14
15@Id
16@Column(name="ID")
17privateintid;
18
19@Column(name="name")
20privateStringname;
21
22@Column(name="sex")
23privateStringsex;
24
25publicvoidsetName(Stringname){
26this.name=name;
27}
28publicStringgetSex(){
29returnsex;
30}
31publicvoidsetSex(Stringsex){
32this.sex=sex;
33}
34
35}
并在数据库创建people表格,添加相应的字段。
然后在dao包中创建DemoDao.class:
1packagecom.hcoding.demo.dao;
2
3importjavax.annotation.Resource;
4
5importorg.hibernate.SessionFactory;
6importorg.springframework.stereotype.Repository;
7
8importcom.hcoding.demo.model.People;
9
10@Repository("demoDao")
11publicclassDemoDaoextendsBaseSupportDao{
12
13@Resource(name="sessionFactory")
14privateSessionFactorysessionFactory;
15
16/**
17*保存对象
18*@paramp
19*@return
20*/
21publicPeoplesave(Peoplep){
22return(People)sessionFactory.getCurrentSession().save(p);
23}
24
25}
在service包中创建DemoServic.class:
1packagecom.hcoding.demo.service;
2
3importjava.util.HashSet;
4importjava.util.Set;
5
6importjavax.annotation.Resource;
7
8importorg.springframework.data.redis.core.RedisTemplate;
9importorg.springframework.stereotype.Service;
10importorg.springframework.transaction.annotation.Transactional;
11
12importcom.hcoding.demo.dao.DemoDao;
13importcom.hcoding.demo.model.Book;
14importcom.hcoding.demo.model.People;
15
16@Service("demoService")
17publicclassDemoService{
18
19@Resource(name="demoDao")
20privateDemoDaodemoDao;;
21
22@Transactional
23publicvoidsave(Peoplep){
24demoDao.save(p);
25}
26
27publicPeoplenewPeople(){
28Peoplep=newPeople();
29p.setName("小白");
30p.setSex("男");
31returnp;
32}
33}
注意点:在save方法上加@Transactional注解来开启事务。
在DemoController.class中调用save方法保存数据:
1packagecom.hcoding.demo.controller;
2
3importjava.util.HashMap;
4importjava.util.Map;
5importjava.util.concurrent.TimeUnit;
6
7importjavax.annotation.Resource;
8importjavax.servlet.http.HttpServletRequest;
9
10importorg.springframework.stereotype.Controller;
11importorg.springframework.web.bind.annotation.RequestMapping;
12importorg.springframework.web.servlet.ModelAndView;
13
14importcom.alibaba.fastjson.JSON;
15importcom.hcoding.demo.model.People;
16importcom.hcoding.demo.service.DemoService;
17
18@Controller
19publicclassDemoController{
20
21@Resource(name="demoService")
22privateDemoServicedemoService;
23
24@RequestMapping("/test")
25publicStringtest(){
26Peoplep=demoService.newPeople();
27demoService.save(p);
28return"test";
29}
30
31}
启动服务器,访问项目。刷新数据库,如果数据保存到数据库中了,说明框架搭建完成。
6.总结
以上就是框架整合的全过程,也是自己看了很多教程和自己搭了很多遍后整理的,基本上配置文件是比较整洁,没有多余的内容(因为很容易由于不懂原理,依样画葫芦莫名其妙写了些没有的内容进去),大部分内容也有说明作用,也说了一些需要注意的,我自己犯过错地方。当然,如果你是第一次搭建框架,那么问题远没有那么少,遇到问题就多百度吧,当然,在这之前对于spring框架还是要多了解一点会更利于学习。另外,项目是全注解的,所以对注解不太了解也可以自行百度一下。
本文内容总结:1.新建一个mavenweb项目。(没用过maven的可以i先去了解一下),2.pom文件,导入jar包,3.配置文件,4.spring-mvc和spring整合,5.spring和hibernate整合,6.总结,
原文链接:https://www.cnblogs.com/xuezhajun/p/7687230.html