基于SpringBoot与Mybatis实现SpringMVC Web项目

2025-05-29 0 102

一、热身

一个现实的场景是:当我们开发一个web工程时,架构师和开发工程师可能更关心项目技术结构上的设计。而几乎所有结构良好的软件(项目)都使用了分层设计。分层设计是将项目按技术职能分为几个内聚的部分,从而将技术或接口的实现细节隐藏起来。

基于SpringBoot与Mybatis实现SpringMVC Web项目

从另一个角度上来看,结构上的分层往往也能促进了技术人员的分工,可以使开发人员更专注于某一层业务与功能的实现,比如前端工程师只关心页面的展示与交互效果(例如专注于html,js等),而后端工程师只关心数据和业务逻辑的处理(专注于java,mysql等)。两者之间通过标准接口(协议)进行沟通。

在实现分层的过程中我们会使用一些框架,例如springmvc。但利用框架带来了一些使用方面的问题。我们经常要做的工作就是配置各种xml文件,然后还需要搭建配置tomcat或者jetty作为容器来运行这个工程。每次构建一个新项目,都要经历这个流程。更为不幸的是有时候前端人员为了能在本地调试或测试程序,也需要先配置这些环境,或者需要后端人员先实现一些服务功能。这就和刚才提到的“良好的分层结构”相冲突。

每一种技术和框架都有一定的学习曲线。开发人员需要了解具体细节,才知道如何把项目整合成一个完整的解决方案。事实上,一个整合良好的项目框架不仅仅能实现技术、业务的分离,还应该关注并满足开发人员的“隔离”。

为了解决此类问题,便产生了spring boot这一全新框架。spring boot就是用来简化spring应用的搭建以及开发过程。该框架致力于实现免xml配置,提供便捷,独立的运行环境,实现“一键运行”满足快速应用开发的需求。

与此同时,一个完整的web应用难免少不了数据库的支持。利用jdbc的api需要编写复杂重复且冗余的代码。而使用o/rm(例如hibernate)工具需要基于一些假设和规则,例如最普遍的一个假设就是数据库被恰当的规范了。这些规范在现实项目中并非能完美实现。由此,诞生了一种混合型解决方案——mybatismybatis是一个持久层框架,它从各种数据库访问工具中汲取大量优秀的思想,适用于任何大小和用途的数据库。根据官方文档的描述:mybatis 是支持定制化 sql、存储过程以及高级映射的优秀的持久层框架。mybatis 避免了几乎所有的 jdbc 代码和手动设置参数以及获取结果集。mybatis 可以对配置和原生map使用简单的 xml 或注解,将接口和 java 的 pojos(plain old java objects,普通的 java对象)映射成数据库中的记录。

最后,再回到技术结构分层上,目前主流倡导的设计模式为mvc,即模型(model)-视图(view)-控制器(controller)。实现该设计模式的框架有很多,例如struts。而前文提到的springmvc是另一个更为优秀,灵活易用的mvc框架。 springmvc是一种基于java的以请求为驱动类型的轻量级web框架,其目的是将web层进行解耦,即使用“请求-响应”模型,从工程结构上实现良好的分层,区分职责,简化web开发。

目前,对于如何把这些技术整合起来形成一个完整的解决方案,并没有相关的最佳实践。将spring boot和mybatis两者整合使用的资料和案例较少。因此,本文提供(介绍)一个完整利用springboot和mybatis来构架web项目的案例。该案例基于springmvc架构提供完整且简洁的实现demo,便于开发人员根据不同需求和业务进行拓展。

补充提示,spring boot 推荐采用基于 java 注解的配置方式,而不是传统的 xml。只需要在主配置 java 类上添加“@enableautoconfiguration”注解就可以启用自动配置。spring boot 的自动配置功能是没有侵入性的,只是作为一种基本的默认实现。开发人员可以通过定义其他 bean 来替代自动配置所提供的功能,例如在配置本案例数据源(datasource)时,可以体会到该用法。

二、实践

一些说明:

项目ide采用intellij(主要原因在于intellij颜值完爆eclipse,谁叫这是一个看脸的时代)

工程依赖管理采用个人比较熟悉的maven(事实上springboot与groovy才是天生一对)

1.预览:

(1)github地址

https://github.com/djmpink/springboot-mybatis

git :https://github.com/djmpink/springboot-mybatis.git

(2)完整项目结构

基于SpringBoot与Mybatis实现SpringMVC Web项目

(3)数据库

数据库名:test

【user.sql】

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16
set foreign_key_checks=0;

-- ----------------------------

-- table structure for user

-- ----------------------------

drop table if exists `user`;

create table `user` (

`id` int(11) not null,

`name` varchar(255) default null,

`age` int(11) default null,

`password` varchar(255) default null,

primary key (`id`)

) engine=innodb default charset=latin1;

-- ----------------------------

-- records of user

-- ----------------------------

insert into `user` values ('1', '7player', '18', '123456');

2.maven配置

完整的【pom.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

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
<?xml version="1.0" encoding="utf-8"?>

<project xmlns="http://maven.apache.org/pom/4.0.0"

xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"

xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelversion>4.0.0</modelversion>

<groupid>cn.7player.framework</groupid>

<artifactid>springboot-mybatis</artifactid>

<version>1.0-snapshot</version>

<parent>

<groupid>org.springframework.boot</groupid>

<artifactid>spring-boot-starter-parent</artifactid>

<version>1.2.5.release</version>

</parent>

<properties>

<project.build.sourceencoding>utf-8</project.build.sourceencoding>

<java.version>1.7</java.version>

</properties>

<dependencies>

<!--spring boot-->

<!--支持 web 应用开发,包含 tomcat 和 spring-mvc。 -->

<dependency>

<groupid>org.springframework.boot</groupid>

<artifactid>spring-boot-starter-web</artifactid>

</dependency>

<!--模板引擎-->

<dependency>

<groupid>org.springframework.boot</groupid>

<artifactid>spring-boot-starter-thymeleaf</artifactid>

</dependency>

<!--支持使用 jdbc 访问数据库-->

<dependency>

<groupid>org.springframework.boot</groupid>

<artifactid>spring-boot-starter-jdbc</artifactid>

</dependency>

<!--添加适用于生产环境的功能,如性能指标和监测等功能。 -->

<dependency>

<groupid>org.springframework.boot</groupid>

<artifactid>spring-boot-starter-actuator</artifactid>

</dependency>

<!--mybatis-->

<dependency>

<groupid>org.mybatis</groupid>

<artifactid>mybatis-spring</artifactid>

<version>1.2.2</version>

</dependency>

<dependency>

<groupid>org.mybatis</groupid>

<artifactid>mybatis</artifactid>

<version>3.2.8</version>

</dependency>

<!--mysql / datasource-->

<dependency>

<groupid>org.apache.tomcat</groupid>

<artifactid>tomcat-jdbc</artifactid>

</dependency>

<dependency>

<groupid>mysql</groupid>

<artifactid>mysql-connector-java</artifactid>

</dependency>

<!--json support-->

<dependency>

<groupid>com.alibaba</groupid>

<artifactid>fastjson</artifactid>

<version>1.1.43</version>

</dependency>

<!--swagger support-->

<dependency>

<groupid>com.mangofactory</groupid>

<artifactid>swagger-springmvc</artifactid>

<version>0.9.5</version>

</dependency>

</dependencies>

<build>

<plugins>

<plugin>

<groupid>org.springframework.boot</groupid>

<artifactid>spring-boot-maven-plugin</artifactid>

</plugin>

</plugins>

</build>

<repositories>

<repository>

<id>spring-milestone</id>

<url>https://repo.spring.io/libs-release</url>

</repository>

</repositories>

<pluginrepositories>

<pluginrepository>

<id>spring-milestone</id>

<url>https://repo.spring.io/libs-release</url>

</pluginrepository>

</pluginrepositories>

</project>

3.主函数

【application.java】包含main函数,像普通java程序启动即可。

此外,该类中还包含和数据库相关的datasource,sqlseesion配置内容。

注:@mapperscan(“cn.no7player.mapper”) 表示mybatis的映射路径(package路径)

?

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
package cn.no7player;

import org.apache.ibatis.session.sqlsessionfactory;

import org.apache.log4j.logger;

import org.mybatis.spring.sqlsessionfactorybean;

import org.mybatis.spring.annotation.mapperscan;

import org.springframework.boot.springapplication;

import org.springframework.boot.autoconfigure.enableautoconfiguration;

import org.springframework.boot.autoconfigure.springbootapplication;

import org.springframework.boot.context.properties.configurationproperties;

import org.springframework.context.annotation.bean;

import org.springframework.context.annotation.componentscan;

import org.springframework.core.io.support.pathmatchingresourcepatternresolver;

import org.springframework.jdbc.datasource.datasourcetransactionmanager;

import org.springframework.transaction.platformtransactionmanager;

import javax.sql.datasource;

@enableautoconfiguration

@springbootapplication

@componentscan

@mapperscan("cn.no7player.mapper")

public class application {

private static logger logger = logger.getlogger(application.class);

//datasource配置

@bean

@configurationproperties(prefix="spring.datasource")

public datasource datasource() {

return new org.apache.tomcat.jdbc.pool.datasource();

}

//提供sqlseesion

@bean

public sqlsessionfactory sqlsessionfactorybean() throws exception {

sqlsessionfactorybean sqlsessionfactorybean = new sqlsessionfactorybean();

sqlsessionfactorybean.setdatasource(datasource());

pathmatchingresourcepatternresolver resolver = new pathmatchingresourcepatternresolver();

sqlsessionfactorybean.setmapperlocations(resolver.getresources("classpath:/mybatis/*.xml"));

return sqlsessionfactorybean.getobject();

}

@bean

public platformtransactionmanager transactionmanager() {

return new datasourcetransactionmanager(datasource());

}

/**

* main start

*/

public static void main(string[] args) {

springapplication.run(application.class, args);

logger.info("============= springboot start success =============");

}

}

4.controller

请求入口controller部分提供三种接口样例:视图模板,json,restful风格

(1)视图模板

返回结果为视图文件路径。视图相关文件默认放置在路径 resource/templates下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19
package cn.no7player.controller;

import org.apache.log4j.logger;

import org.springframework.stereotype.controller;

import org.springframework.ui.model;

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

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

@controller

public class hellocontroller {

private logger logger = logger.getlogger(hellocontroller.class);

/*

* http://localhost:8080/hello?name=cn.7player

*/

@requestmapping("/hello")

public string greeting(@requestparam(value="name", required=false, defaultvalue="world") string name, model model) {

logger.info("hello");

model.addattribute("name", name);

return "hello";

}

}

(2)json

返回json格式数据,多用于ajax请求。

?

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 cn.no7player.controller;

import cn.no7player.model.user;

import cn.no7player.service.userservice;

import org.apache.log4j.logger;

import org.springframework.beans.factory.annotation.autowired;

import org.springframework.stereotype.controller;

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

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

@controller

public class usercontroller {

private logger logger = logger.getlogger(usercontroller.class);

@autowired

private userservice userservice;

/*

* http://localhost:8080/getuserinfo

*/

@requestmapping("/getuserinfo")

@responsebody

public user getuserinfo() {

user user = userservice.getuserinfo();

if(user!=null){

system.out.println("user.getname():"+user.getname());

logger.info("user.getage():"+user.getage());

}

return user;

}

}

(3)restful

rest 指的是一组架构约束条件和原则。满足这些约束条件和原则的应用程序或设计就是 restful。

此外,有一款restful接口的文档在线自动生成+功能测试功能软件——swagger ui,具体配置过程可移步《spring boot 利用 swagger 实现restful测试》

?

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
package cn.no7player.controller;

import cn.no7player.model.user;

import com.wordnik.swagger.annotations.apioperation;

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

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

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

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

import java.util.arraylist;

import java.util.list;

@restcontroller

@requestmapping(value="/users")

public class swaggercontroller {

/*

* http://localhost:8080/swagger/index.html

*/

@apioperation(value="get all users",notes="requires noting")

@requestmapping(method=requestmethod.get)

public list<user> getusers(){

list<user> list=new arraylist<user>();

user user=new user();

user.setname("hello");

list.add(user);

user user2=new user();

user.setname("world");

list.add(user2);

return list;

}

@apioperation(value="get user with id",notes="requires the id of user")

@requestmapping(value="/{name}",method=requestmethod.get)

public user getuserbyid(@pathvariable string name){

user user=new user();

user.setname("hello world");

return user;

}

}

5.mybatis

配置相关代码在application.java中体现。

(1)【application.properties】

?

1

2

3

4
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/test?useunicode=true&characterencoding=gbk&zerodatetimebehavior=converttonull

spring.datasource.username=root

spring.datasource.password=123456

spring.datasource.driver-class-name=com.mysql.jdbc.driver

注意,在application.java代码中,配置datasource时的注解

?

1
@configurationproperties(prefix=“spring.datasource”)

表示将根据前缀“spring.datasource”从application.properties中匹配相关属性值。

(2)【usermapper.xml】

mybatis的sql映射文件。mybatis同样支持注解方式,在此不予举例了。

?

1

2

3

4

5

6

7
<?xml version="1.0" encoding="utf-8"?>

<!doctype mapper public "-//mybatis.org//dtd mapper 3.0//en" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="cn.no7player.mapper.usermapper">

<select id="finduserinfo" resulttype="cn.no7player.model.user">

select name, age,password from user;

</select>

</mapper>

(3)接口usermapper

?

1

2

3

4

5
package cn.no7player.mapper;

import cn.no7player.model.user;

public interface usermapper {

public user finduserinfo();

}

三、总结

(1)运行 application.java

(2)控制台输出:

基于SpringBoot与Mybatis实现SpringMVC Web项目

…..(略过无数内容)

基于SpringBoot与Mybatis实现SpringMVC Web项目

(3)访问:

针对三种控制器的访问分别为:

视图:

基于SpringBoot与Mybatis实现SpringMVC Web项目

json:

http://localhost:8080/getuserinfo

基于SpringBoot与Mybatis实现SpringMVC Web项目

restful(使用了swagger):

基于SpringBoot与Mybatis实现SpringMVC Web项目

四、参阅

《Spring Boot – Quick Start》

http://projects.spring.io/spring-boot/#quick-start

mybatis

http://mybatis.github.io/mybatis-3/

《使用 Spring Boot 快速构建 Spring 框架应用》

http://www.ibm.com/developerworks/cn/java/j-lo-spring-boot/

《Using @ConfigurationProperties in Spring Boot》

Using @ConfigurationProperties in Spring Boot

《Springboot-Mybatis-Mysample》

https://github.com/mizukyf/springboot-mybatis-mysample

《Serving Web Content with Spring MVC》

http://spring.io/guides/gs/serving-web-content/

《理解RESTful架构》

http://www.ruanyifeng.com/blog/2011/09/restful

附录:

spring boot 推荐的基础 pom 文件

基于SpringBoot与Mybatis实现SpringMVC Web项目

基于SpringBoot与Mybatis实现SpringMVC Web项目

以上所述是小编给大家介绍的基于springboot与mybatis实现springmvc web项目,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对快网idc网站的支持!

原文链接:http://www.cnblogs.com/onetwo/p/6237181.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 基于SpringBoot与Mybatis实现SpringMVC Web项目 https://www.kuaiidc.com/117388.html

相关文章

发表评论
暂无评论