二、实践

一些说明:

项目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)完整项目结构

(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
49
50
51
52
53
54
55
56
57
58
59
60
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
20
21
22
23
24
25
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
28
29
30
31
32
33
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
36
37
38
39
40
41
42
43
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时的注解

@ConfigurationProperties(prefix=“spring.datasource”)

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

(2)【UserMapper.xml】

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

 
1
2
3
4
5
6
7
8
9
<?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
6
7
package cn.no7player.mapper;
 
import cn.no7player.model.User;
 
public interface UserMapper {
    public User findUserInfo();
}

三、总结

(1)运行 Application.java

(2)控制台输出:

…..(略过无数内容)

(3)访问:

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

视图:

http://localhost:8080/hello?name=7player

Json:

http://localhost:8080/getUserInfo

Restful(使用了swagger):

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

四、参阅

《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》

http://www.javacodegeeks.com/2014/09/using-configurationproperties-in-spring-boot.html?utm_source=tuicool

《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 文件

名称

说明

spring-boot-starter

核心 POM,包含自动配置支持、日志库和对 YAML 配置文件的支持。

spring-boot-starter-amqp

通过 spring-rabbit 支持 AMQP。

spring-boot-starter-aop

包含 spring-aop 和 AspectJ 来支持面向切面编程(AOP)。

spring-boot-starter-batch

支持 Spring Batch,包含 HSQLDB。

spring-boot-starter-data-jpa

包含 spring-data-jpa、spring-orm 和 Hibernate 来支持 JPA。

spring-boot-starter-data-mongodb

包含 spring-data-mongodb 来支持 MongoDB。

spring-boot-starter-data-rest

通过 spring-data-rest-webmvc 支持以 REST 方式暴露 Spring Data 仓库。

spring-boot-starter-jdbc

支持使用 JDBC 访问数据库。

spring-boot-starter-security

包含 spring-security。

spring-boot-starter-test

包含常用的测试所需的依赖,如 JUnit、Hamcrest、Mockito 和 spring-test 等。

spring-boot-starter-velocity

支持使用 Velocity 作为模板引擎。

spring-boot-starter-web

支持 Web 应用开发,包含 Tomcat 和 spring-mvc。

spring-boot-starter-websocket

支持使用 Tomcat 开发 WebSocket 应用。

spring-boot-starter-ws

支持 Spring Web Services。

spring-boot-starter-actuator

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

spring-boot-starter-remote-shell

添加远程 SSH 支持。

spring-boot-starter-jetty

使用 Jetty 而不是默认的 Tomcat 作为应用服务器。

spring-boot-starter-log4j

添加 Log4j 的支持。

spring-boot-starter-logging

使用 Spring Boot 默认的日志框架 Logback。

spring-boot-starter-tomcat

使用 Spring Boot 默认的 Tomcat 作为应用服务器。

转自:http://7player.cn/2015/08/30/%E3%80%90%E5%8E%9F%E5%88%9B%E3%80%91%E5%9F%BA%E4%BA%8Espringboot-mybatis%E5%AE%9E%E7%8E%B0springmvc-web%E9%A1%B9%E7%9B%AE/

 

MVCMyBatisspringSpringBoot

spring boot 实践的更多相关文章

  1. Spring Boot实践——Spring AOP实现之动态代理

    Spring AOP 介绍 AOP的介绍可以查看 Spring Boot实践——AOP实现 与AspectJ的静态代理不同,Spring AOP使用的动态代理,所谓的动态代理就是说AOP框架不会去修改 ...

  2. Spring Boot实践——AOP实现

    借鉴:http://www.cnblogs.com/xrq730/p/4919025.html     https://blog.csdn.net/zhaokejin521/article/detai ...

  3. Spring Boot 实践 :Spring Boot + MyBatis

    Spring Boot 实践系列,Spring Boot + MyBatis . 目的 将 MyBatis 与 Spring Boot 应用程序一起使用来访问数据库. 本次使用的Library spr ...

  4. spring boot 实践总结(转)

    pring Boot是最流行的用于开发微服务的Java框架.在本文主要分享的是在专业开发中使用Spring Boot所采用的最佳实践.这些内容是基于个人经验和一些熟知的Spring Boot专家的文章 ...

  5. Spring Boot实践——用外部配置填充Bean属性的几种方法

    引用:https://blog.csdn.net/qq_17586821/article/details/79802320 spring boot允许我们把配置信息外部化.由此,我们就可以在不同的环境 ...

  6. Spring Boot实践——事件监听

    借鉴:https://blog.csdn.net/Harry_ZH_Wang/article/details/79691994 https://blog.csdn.net/ignorewho/arti ...

  7. Spring Boot实践——基础和常用配置

    借鉴:https://blog.csdn.net/j903829182/article/details/74906948 一.Spring Boot 启动注解说明 @SpringBootApplica ...

  8. Spring Boot实践——Spring Boot 2.0 新特性和发展方向

    出自:https://mp.weixin.qq.com/s/EWmuzsgHueHcSB0WH-3AQw 以Java 8 为基准 Spring Boot 2.0 要求Java 版本必须8以上, Jav ...

  9. Spring Boot实践——Filter实现

    Filter介绍 Filter是Servlet规范规定的,不属于spring框架,也是用于请求的拦截.但是它适合更粗粒度的拦截,在请求前后做一些编解码处理.日志记录等. 一个Filter包括:1).在 ...

随机推荐

  1. STM32系统时钟

    一.时钟树 STM32有4个时钟源: 1)HSE(高速外部时钟源) 外部晶振作为时钟源,范围为4~16MHz,常取为8MHz 2)HSI(高速内部时钟源) 由内部RC振荡器产生,频率为8MHz,但不稳 ...

  2. 简单的网页采集程序(ASP.NET MVC4)

    因为懒人太多,造成现在网页数据采集非常的流行,我也来写个简单的记录一下. 之前写了MVC的基本框架的搭建随笔,后面因为公司太忙,个人感情问题:(,导致不想写了,就写了两篇给删除了,现在就搁浅了, 本人 ...

  3. 记录一次配置unix网络编程环境的过程和遇到的问题

    记录一次搭建unix网络编程环境过程中遇到的问题和总结 计算机环境虚拟机 linuxmint-18-xfce-64bit 1.打开unix网络编程.iso 把目录下的文件复制到某一目录,修改权限,可命 ...

  4. VOIP概述

    简介 VoIP(Voice over Internet Protocol)就是将模拟声音讯号(Voice)数字化,以数据封包(Data Packet)的型式在 IP 数据网络 (IP Network) ...

  5. Waterfall———瀑布流布局插件, 类似于 Pinterest、花瓣、发现啦。

    瀑布流布局插件, 类似于 Pinterest.花瓣.发现啦. En 中文 文档 下载 下载waterfall插件最新版本. 使用 html: <div id="container&qu ...

  6. Hdu 2979 Expensive Drink

    Description There are some water, milk and wine in your kitchen. Your naughty little sister made som ...

  7. shell 基础 $(cd `dirname $0`;pwd)

    $ cd `dirname $0` 和PWD%/* shell变量的一些特殊用法 在命令行状态下单纯执行 $ cd `dirname $0` 是毫无意义的.因为他返回当前路径的"." ...

  8. Java RMI简单例子HelloWorld

    Java RMI 指的是远程方法调用 (Remote Method Invocation).它是一种机制,能够让在某个 Java 虚拟机上的对象调用另一个 Java 虚拟机中的对象上的方法.可以用此方 ...

  9. ListView 的position和id的区别

    我们在使用ListView的时候,一般都会为ListView添加一个响应事件android.widget.AdapterView.OnItemClickListener.本文主要在于对OnItemCl ...

  10. bzoj3238

    都LCP了很显然是要用到后缀数组的 显然前面的那个东西是可以直接算出来的 关键在于LCP的和怎么快速的计算 不难想到穷举height[i],然后判断这个height[i]可能成为多少对后缀的LCP 考 ...