好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

基于spring+springmvc+hibernate 整合深入剖析

三大框架反反复复搭了很多次,虽然每次都能搭起来,但是效率不高。最近重新搭了一次,理顺了思路,整理了需要注意的地方,分享出来。

工具:Eclipse(jdk 1.7) spring和hibernate版本均为4.0以上

推荐使用maven构建项目,相比自己手动导入jar包要方便很多。

1.新建一个maven web项目

(没用过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测试数据/

pom文件:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

< project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://HdhCmsTestw3.org/2001/XMLSchema-instance"

   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" >

   < modelVersion >4.0.0</ modelVersion >

   < groupId >hcoding</ groupId >

   < artifactId >MyWebDemo</ artifactId >

   < packaging >war</ packaging >

   < version >0.0.1-SNAPSHOT</ version >

   < name >MyWebDemo Maven Webapp</ name >

   < url >http://maven.apache.org</ url >

   < dependencies >

     < dependency >

       < groupId >junit</ groupId >

       < artifactId >junit</ artifactId >

       < version >3.8.1</ version >

       < scope >test</ scope >

     </ dependency >

     <!-- spring start -->

     < dependency >

         < groupId >org.springframework</ groupId >

         < artifactId >spring-context</ artifactId >

         < version >4.3.9.RELEASE</ version >

     </ dependency >

     < dependency >

         < groupId >org.springframework</ groupId >

         < artifactId >spring-core</ artifactId >

         < version >4.3.9.RELEASE</ version >

     </ dependency >

     < dependency >

         < groupId >org.springframework</ groupId >

         < artifactId >spring-beans</ artifactId >

         < version >4.3.9.RELEASE</ version >

     </ dependency >

     < dependency >

         < groupId >org.springframework</ groupId >

         < artifactId >spring-web</ artifactId >

         < version >4.3.9.RELEASE</ version >

     </ dependency >

     < dependency >

         < groupId >org.springframework</ groupId >

         < artifactId >spring-aspects</ artifactId >

         < version >4.3.9.RELEASE</ version >

     </ dependency >

     < dependency >

         < groupId >org.springframework</ groupId >

         < artifactId >spring-orm</ artifactId >

         < version >4.3.9.RELEASE</ version >

     </ dependency >

     <!-- spring end -->

     <!-- springmvc start -->

     < dependency >

         < groupId >org.springframework</ groupId >

         < artifactId >spring-webmvc</ artifactId >

         < version >4.3.9.RELEASE</ version >

     </ dependency >

     <!-- springmvc end -->

     <!-- loging start -->

     < dependency >

         < groupId >org.slf4j</ groupId >

         < artifactId >slf4j-api</ artifactId >

         < version >1.7.6</ version >

     </ dependency >

     <!-- loging end -->

     < dependency >

         < groupId >aspectj</ groupId >

         < artifactId >aspectjrt</ artifactId >

         < version >1.5.3</ version >

     </ dependency >

     < dependency >

         < groupId >org.aspectj</ groupId >

         < artifactId >aspectjtools</ artifactId >

         < version >1.8.7</ version >

     </ dependency >

     < dependency >

         < groupId >javax.servlet</ groupId >

         < artifactId >jstl</ artifactId >

         < version >1.2</ version >

         < scope >runtime</ scope >

     </ dependency >

     < dependency >

         < groupId >javax.annotation</ groupId >

         < artifactId >javax.annotation-api</ artifactId >

         < version >1.2</ version >

     </ dependency >

     < dependency >

         < groupId >javax.servlet</ groupId >

         < artifactId >servlet-api</ artifactId >

         < version >2.5</ version >

     </ dependency >

     <!-- hibernate start -->

     < dependency >

         < groupId >org.hibernate</ groupId >

         < artifactId >hibernate-core</ artifactId >

         < version >4.2.3.Final</ version >

     </ dependency >

     <!-- hibernate end -->

     <!--c3p0 start -->

     < dependency >

         < groupId >c3p0</ groupId >

         < artifactId >c3p0</ artifactId >

         < version >0.9.1.2</ version >

     </ dependency >

     <!-- c3p0 end -->

     <!-- mysql start-->

     < dependency >

         < groupId >mysql</ groupId >

         < artifactId >mysql-connector-java</ artifactId >

         < version >5.1.35</ version >

     </ dependency >

     <!-- mysql end-->

   </ dependencies >

     < build >

         < finalName >MyWebDemo</ finalName >

     </ build >

</ project >

其中,注释块 <spring> <springmvc> <hibernate>中的依赖导入了框架核心jar包,我们可以提前导入,其他的我们可以根据提示或者需求进行改动。

比如,我的项目中使用的是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

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

< beans xmlns = "http://HdhCmsTestspringframework.org/schema/beans"

        xmlns:xsi = "http://HdhCmsTestw3.org/2001/XMLSchema-instance"

        xmlns:context = "http://HdhCmsTestspringframework.org/schema/context"

        xmlns:mvc = "http://HdhCmsTestspringframework.org/schema/mvc"

        xsi:schemaLocation="http://HdhCmsTestspringframework.org/schema/beans

         http://HdhCmsTestspringframework.org/schema/beans/spring-beans-4.1.xsd

         http://HdhCmsTestspringframework.org/schema/context

         http://HdhCmsTestspringframework.org/schema/context/spring-context-4.1.xsd

         http://HdhCmsTestspringframework.org/schema/mvc

         http://HdhCmsTestspringframework.org/schema/mvc/spring-mvc-4.1.xsd">

     < mvc:annotation-driven />

     < context:component-scan base-package = "com.hcoding.demo" >

         < context:include-filter type = "annotation"

             expression = "org.springframework.stereotype.Controller" />

         <!-- 排除@service注解的类 -->

         < context:exclude-filter type = "annotation"

             expression = "org.springframework.stereotype.Service" />

     </ context:component-scan >

     <!-- 对模型视图名称的解析,在请求时模型视图名称添加前后缀 -->

     < bean id = "viewResolver" class = "org.springframework.web.servlet.view.InternalResourceViewResolver" >

         < property name = "viewClass" value = "org.springframework.web.servlet.view.JstlView" />

         < property name = "prefix" value = "demo/" /> <!-- 前缀 -->

         < property name = "suffix" value = ".jsp" />   <!-- 后缀 -->

     </ bean >

     <!-- 对静态资源的映射-->

     < mvc:resources mapping = "/js/**" location = "/resources/js/" />

     < mvc:resources mapping = "/css/**" location = "/resources/css/" />

     < mvc:resources mapping = "/img/**" location = "/resources/img/" />

</ beans >

这是spring-mvc基本的配置,主要是对请求和静态资源映射的配置。

注意点:

1.需要特别注意的是扫描包时要排除service层的类,不然在整合hibernate后,项目运行时会报错。

具体原因看一下 这篇文章

2.然后就是如果你的包名和结构不一样的,那么扫描的包地址也要记得更换。

然后是web.xml配置文件:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

<!DOCTYPE web-app PUBLIC

  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

  "http://java.sun测试数据/dtd/web-app_2_3.dtd" >

< web-app >

   < display-name >MyWebDemo</ display-name >

     <!-- 统一编码 解决中文乱码问题-->

     < filter >

         < filter-name >charsetEncoding</ 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 >charsetEncoding</ filter-name >

         < url-pattern >/*</ url-pattern >

     </ filter-mapping >

     <!-- spring MVC 配置-->

     < servlet >

          < servlet-name >spring</ servlet-name >

          < servlet-class >org.springframework.web.servlet.DispatcherServlet</ servlet-class >

          < init-param >

             < param-name >contextConfigLocation</ param-name >

             <!-- 此处指向的的是SpringMVC的配置文件 如果配置文件地址和名称不一样需要更改-->

             < param-value >classpath:spring-mvc.xml</ param-value >

          </ init-param >

          <!--配置容器在启动的时候就加载这个servlet并实例化-->

          < load-on-startup >1</ load-on-startup >

     </ servlet >

     < servlet-mapping >

         < servlet-name >spring</ servlet-name >

         < url-pattern >/</ url-pattern >

     </ servlet-mapping >

     <!-- spring MVC config end-->

</ 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:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

package com.hcoding.demo.controller;

import java.util.HashMap;

import java.util.Map;

import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

import com.hcoding.demo.model.People;

import com.hcoding.demo.service.DemoService;

@Controller

public class DemoController{

     @RequestMapping ( "/test" )

     public String test(){

         return "test" ;

     }

}

然后在demo文件夹中创建demo.jsp:

?

1

2

3

4

5

6

7

8

9

10

11

<%@ page language="java" contentType="text/html; UTF-8"

pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://HdhCmsTestw3.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 >

< p >这是测试页面。</ p >

</ html >

启动项目,在浏览器中输入地址:http://localhost:8080/(项目名)/test 。成功可以看到页面。

5.spring和hibernate整合

datasource.xml配置文件:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

<? xml version = "1.0" encoding = "UTF-8" ?>

< beans xmlns = "http://HdhCmsTestspringframework.org/schema/beans"

     xmlns:xsi = "http://HdhCmsTestw3.org/2001/XMLSchema-instance"

     xmlns:jee = "http://HdhCmsTestspringframework.org/schema/jee"

     xmlns:tx = "http://HdhCmsTestspringframework.org/schema/tx"

     xmlns:context = "http://HdhCmsTestspringframework.org/schema/context"

     xmlns:aop = "http://HdhCmsTestspringframework.org/schema/aop"

     xsi:schemaLocation="

     http://HdhCmsTestspringframework.org/schema/aop

    http://HdhCmsTestspringframework.org/schema/aop/spring-aop-3.2.xsd

    http://HdhCmsTestspringframework.org/schema/beans

    http://HdhCmsTestspringframework.org/schema/beans/spring-beans-3.2.xsd

    http://HdhCmsTestspringframework.org/schema/tx

    http://HdhCmsTestspringframework.org/schema/tx/spring-tx-3.2.xsd

    http://HdhCmsTestspringframework.org/schema/jee

    http://HdhCmsTestspringframework.org/schema/jee/spring-jee-3.2.xsd

    http://HdhCmsTestspringframework.org/schema/context

    http://HdhCmsTestspringframework.org/schema/context/spring-context-3.2.xsd">

    <!--配置数据源 这里是使用的是c3p0连接池-->

    < bean id = "dataSource" class = "com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method = "close" >

        < property name = "driverClass" value = "${jdbc.driver}" />  <!--数据库连接驱动-->

        < property name = "jdbcUrl" value = "${jdbc.url}" />     <!--数据库地址-->

        < property name = "user" value = "${jdbc.username}" />   <!--用户名-->

        < property name = "password" value = "${jdbc.password}" />   <!--密码-->

        < property name = "maxPoolSize" value = "40" />      <!--最大连接数-->

        < property name = "minPoolSize" value = "1" />       <!--最小连接数-->

        < property name = "initialPoolSize" value = "10" />      <!--初始化连接池内的数据库连接-->

        < property name = "maxIdleTime" value = "20" />  <!--最大空闲时间-->

    </ bean >

    <!--配置session工厂-->

    < bean id = "sessionFactory" class = "org.springframework.orm.hibernate4.LocalSessionFactoryBean" >

        < property name = "dataSource" ref = "dataSource" />

        < property name = "packagesToScan" value = "com.hcoding.demo" />

        < property name = "hibernateProperties" >

            < props >38                 < prop key = "hibernate.hbm2ddl.auto" >${hibernate.hbm2ddl.auto}</ prop > <!--hibernate根据实体自动生成数据库表-->

                < prop key = "hibernate.dialect" >${hibernate.dialect}</ prop >   <!--指定数据库方言-->

                < prop key = "hibernate.show_sql" >${hibernate.show_sql}</ prop >     <!--在控制台显示执行的数据库操作语句-->

                < prop key = "hibernate.format_sql" >${hibernate.format_sql}</ prop >     <!--在控制台显示执行的数据哭操作语句(格式)-->

            </ props >

        </ property >

    </ bean >

   

    <!-- 事务配置 声明式事务-->

    < bean id = "transactionManager"

        class = "org.springframework.orm.hibernate4.HibernateTransactionManager" >

        < property name = "sessionFactory" ref = "sessionFactory" />

    </ bean >

    <!-- 使用annotation定义事务 -->

    < tx:annotation-driven transaction-manager = "transactionManager" />

</ beans >

datasource.properties文件:

?

1

2

3

4

5

6

7

8

9

10

# database connection config

jdbc.driver = com.mysql.jdbc.Driver

jdbc.url = jdbc:mysql://localhost:3306/demo?useUnicode= true &characterEncoding=utf-8

jdbc.username = root

jdbc. password = 123456

#hibernate config

hibernate.dialect = org.hibernate.dialect.MySQLDialect

hibernate.show_sql = true

hibernate.format_sql = true

hibernate.hbm2ddl.auto = update

beans.xml文件:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

<? xml version = "1.0" encoding = "UTF-8" ?>

< beans xmlns = "http://HdhCmsTestspringframework.org/schema/beans"

     xmlns:xsi = "http://HdhCmsTestw3.org/2001/XMLSchema-instance" xmlns:context = "http://HdhCmsTestspringframework.org/schema/context"

     xmlns:p = "http://HdhCmsTestspringframework.org/schema/p" xmlns:cache = "http://HdhCmsTestspringframework.org/schema/cache"

     xsi:schemaLocation="

         http://HdhCmsTestspringframework.org/schema/beans

         http://HdhCmsTestspringframework.org/schema/beans/spring-beans-3.0.xsd

         http://HdhCmsTestspringframework.org/schema/context

         http://HdhCmsTestspringframework.org/schema/context/spring-context-3.0.xsd

         http://HdhCmsTestspringframework.org/schema/cache

         http://HdhCmsTestspringframework.org/schema/cache/spring-cache-3.1.xsd">

     <!-- 注解 -->

     < context:annotation-config />

     <!--扫描-->

     < context:component-scan base-package = "com.hcoding.demo" >

         < context:exclude-filter type = "annotation"

             expression = "org.springframework.stereotype.Controller" />

     </ context:component-scan >

     <!-- 导入多个Properties配置文件 -->

     < bean id = "propertyConfigurer" class = "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >

         < property name = "locations" >

             < list >

                 <!--要是有多个配置文件,只需在这里继续添加即可 -->

                 < value >classpath:datasource.properties</ value >

             </ list >

         </ property >

     </ bean >

31     <!-- 加载数据源组件 -->         32     < import resource = "classpath:datasource.xml" />33     34 </ beans >

注意点: 在xml导入properties文件是比较常见,将一些相关的配置数据写到properyties文件中也是常用的方法,利于修改。

常见的另一种导入propertise的方法:在<context:property-placeholder location="classpath:/datasource.properties" />。这种方法spring默认值只导入一个properties,

当有多个properties文件需要导入时,则需要使用另一种方法:

?

1

2

3

4

5

6

7

8

9

10

<!-- 导入多个Properties配置文件 -->

  < bean id = "propertyConfigurer" class = "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >

      < property name = "locations" >

          < list >

              <!--要是有多个配置文件,只需在这里继续添加即可 -->

              < value >classpath:datasource.properties</ value >               

              < value >classpath:redis.properties</ value >

          </ list >

      </ property >

</ bean >

个人比较推荐这种,随着项目扩展,需要导入的配置增多,肯定不止一个properties文件,这种方法更通用。

注意点: datasource.properties文件中的数据库地址,用户和密码根据自己的情况做相应的修改。

修改之前的web.xml文件:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

<!DOCTYPE web-app PUBLIC

  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

  "http://java.sun测试数据/dtd/web-app_2_3.dtd" >

< web-app >

   < display-name >MyWebDemo</ display-name >

     <!-- 统一编码 解决中文乱码问题-->

     < filter >

         < filter-name >charsetEncoding</ 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 >charsetEncoding</ filter-name >

         < url-pattern >/*</ url-pattern >

     </ filter-mapping >

     <!-- spring MVC 配置-->

     < servlet >

          < servlet-name >spring</ servlet-name >

          < servlet-class >org.springframework.web.servlet.DispatcherServlet</ servlet-class >

          < init-param >

             < param-name >contextConfigLocation</ param-name >

             <!-- 此处指向的的是SpringMVC的配置文件 -->

             < param-value >classpath:spring-mvc.xml</ param-value >

          </ init-param >

          <!--配置容器在启动的时候就加载这个servlet并实例化-->

          < load-on-startup >1</ load-on-startup >

     </ servlet >

     < servlet-mapping >

         < servlet-name >spring</ servlet-name >

         < url-pattern >/</ url-pattern >

     </ servlet-mapping >

     <!-- spring MVC config end-->

     <!-- 加载spring配置文件 -->

     < context-param >

         < param-name >contextConfigLocation</ param-name >

         < param-value >classpath:beans.xml</ param-value >

     </ context-param >

     <!-- listener -->

     < listener >

         < listener-class >org.springframework.web.context.ContextLoaderListener</ listener-class >

     </ listener >

</ web-app >

这就是spring整合hibernate所需要配置的四个文件。文件的加载顺序和包含关系:web.xml→bans.xml→datasource.xml→datasource.properties

注意点: 如果你的配置文件名称和存放位置不同,那么你也需要相应的修改。

注意点: 一定要记得配置事务,否则操作数据库时项目可能不会报错,但数据库中的数据将不会更新(删除或者修改)。具体可以自行百度事务相关的知识。

配置完成后写个例子测试一下。

在model包中创建People.class:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

package com.hcoding.demo.model;

import java.util.Set;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.Id;

import javax.persistence.Table;

import javax.persistence.Transient;

@Entity

@Table (name= "people" )

public class People {

     @Id

     @Column (name= "ID" )

     private int id;

     @Column (name= "name" )

     private String name;

     @Column (name= "sex" )

     private String sex;

     public void setName(String name) {

         this .name = name;

     }

     public String getSex() {

         return sex;

     }

     public void setSex(String sex) {

         this .sex = sex;

     }

}

并在数据库创建people表格,添加相应的字段。

然后在dao包中创建DemoDao.class:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

package com.hcoding.demo.dao;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;

import org.springframework.stereotype.Repository;

import com.hcoding.demo.model.People;

@Repository ( "demoDao" )

public class DemoDao extends BaseSupportDao{

     @Resource (name= "sessionFactory" )

     private SessionFactory sessionFactory;

     /**

      * 保存对象

      * @param p

      * @return

      */

     public People save(People p){

         return (People) sessionFactory.getCurrentSession().save(p);

     }

}

在service包中创建DemoServic.class:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

package com.hcoding.demo.service;

import java.util.HashSet;

import java.util.Set;

import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;

import com.hcoding.demo.dao.DemoDao;

import com.hcoding.demo.model.Book;

import com.hcoding.demo.model.People;

@Service ( "demoService" )

public class DemoService {

     @Resource (name= "demoDao" )

     private DemoDao demoDao;;

     @Transactional

     public void save(People p){

        demoDao.save(p);

     }

     public People newPeople(){

         People p= new People();

         p.setName( "小白" );

         p.setSex( "男" );

         return p;

     }

  }

 

注意点: 在save方法上加@Transactional注解来开启事务。

在DemoController.class中调用save方法保存数据:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

package com.hcoding.demo.controller;

import java.util.HashMap;

import java.util.Map;

import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;

import com.hcoding.demo.model.People;

import com.hcoding.demo.service.DemoService;

@Controller

public class DemoController{

     @Resource (name= "demoService" )

     private DemoService demoService;

     @RequestMapping ( "/test" )

     public String test(){

         People p=demoService.newPeople();

         demoService.save(p);

         return "test" ;

     }

}

启动服务器,访问项目。刷新数据库,如果数据保存到数据库中了,说明框架搭建完成。

6.总结

以上就是框架整合的全过程,也是自己看了很多教程和自己搭了很多遍后整理的,基本上配置文件是比较整洁,没有多余的内容(因为很容易由于不懂原理,依样画葫芦莫名其妙写了些没有的内容进去),大部分内容也有说明作用,也说了一些需要注意的,我自己犯过错地方。

当然,如果你是第一次搭建框架,那么问题远没有那么少,遇到问题就多百度吧,当然,在这之前对于spring框架还是要多了解一点会更利于学习。另外,项目是全注解的,所以对注解不太了解也可以自行百度一下。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

原文链接:https://HdhCmsTestcnblogs测试数据/xuezhajun/p/7687230.html

查看更多关于基于spring+springmvc+hibernate 整合深入剖析的详细内容...

  阅读:16次