SpringBoot专栏:集成mybatis以及restful风格样例演示(第8讲)

重点讲解下restfull风格,然后快速集成下mybatis,最后会提供下项目实战中一年应用的样例,欢迎点评

什么是REST

一种软件架构风格、设计风格,而不是标准,只是提供了一组设计原则和约束条件。它主要用于客户端和服务器交互类的软件。基于这个风格设计的软件可以更简洁,更有层次,更易于实现缓存等机制。

理解RESTful

  要理解RESTful架构,需要理解Representational State Transfer这个词组到底是什么意思,它的每一个词都有些什么涵义。

下面我们结合REST原则,围绕资源展开讨论,从资源的定义、获取、表述、关联、状态变迁等角度,列举一些关键概念并加以解释。

  • 资源与URI
  • 统一资源接口
  • 资源的表述
  • 资源的链接
  • 状态的转移

要从以上几点去理解restful风格,要是长篇描述或许一篇文章也无法描述清楚,我们从实战出发,只需要掌握要要点即可,随着深入我们会有更深的理解。

1.案例中的Controller层会涉及GET,DELETE,PUT和POST的典型用法

2.我们先来具体看下RESTful风格的url,比如我要查询商品信息,那么

非REST的url:http://.../queryGoods?id=1001&type=t01

REST的url: http://.../t01/goods/1001

可以看出REST特点:url简洁,将参数通过url传到服务器,而传统的url比较啰嗦,而且现实中浏览器地址栏会拼接一大串字符,想必你们都见过吧。但是采用REST的风格就会好很多,现在很多的网站已经采用这种风格了,这也是潮流方向,典型的就是url的短化转换


集成步骤:

在pom文件引入mybatis-spring-boot-starter的依赖

   <!--新增-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

引入数据库连接依赖:

<!-- alibaba的druid数据库连接池 -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.9</version>
</dependency>

引入数据源

#数据库配置
spring:
  application:
    name: limp-framework-provider
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://115.28.166.xx:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false
    username: root
    password: test
    initialSize: 3
    minIdle: 3
    maxActive: 20
    # 配置获取连接等待超时的时间
    maxWait: 60000
    # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    timeBetweenEvictionRunsMillis: 60000
    # 配置一个连接在池中最小生存的时间,单位是毫秒
    minEvictableIdleTimeMillis: 3600000
    validationQuery: select 'x'
    testWhileIdle: true
    testOnBorrow: true
    testOnReturn: true
    # 打开PSCache,并且指定每个连接上PSCache的大小
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
    # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    filters: stat,wall,slf4j
    # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
    # 合并多个DruidDataSource的监控数据
    #useGlobalDataSourceStat: true

mybatis配置

mybatis:
  config-location: classpath:mybatis/mybatis.cfg.xml        # mybatis配置文件所在路径
  type-aliases-package: com.limp.framework.boss.domain    # 所有Entity别名类所在包
  mapper-locations: classpath:com/limp/framework/boss/persistence/oracle/*.xml,classpath:com/limp/framework/boss/persistence/mysql/*.xml             # mapper映射文件

Controller、Service层、Dao代码

采用resutful风格:

Controller层:主要注意增删改查 四种方式()


package com.limp.framework.boss.controller;

import com.limp.framework.boss.domain.UserInfo;
import com.limp.framework.boss.service.UserInfoService;
import com.limp.framework.core.bean.Pager;
import com.limp.framework.core.bean.Result;
import com.limp.framework.core.bean.ResultCode;
import com.limp.framework.core.constant.Constant;
import com.limp.framework.core.constant.ResultMsg;
import com.limp.framework.utils.StrUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * demo相关操作
 * @author:shinians email:shiniandate@163.com
 * @description:
 * @date:Created in 22:21 2018/6/2
 * @modified By:
 * @RestController:是controller和ResponseBody的集合
 */
@RestController
@RequestMapping("/systemdemo")
public class DemoDomainController extends BaseController {
    private Logger loger= LoggerFactory.getLogger(DemoDomainController.class);

    @Autowired
    UserInfoService userInfoService;

    /**
     * 设置默认页面显示的条数
     */
    public static  final Integer DEFAULT_ROW=10;


    /**
     * 新增实体类信息
     * @param domain
     * @return
     */
    @RequestMapping(value = "/domain",method= RequestMethod.POST)
    public String saveUserInfo(UserInfo domain) {
        loger.debug("/***新增实体类信息**/");
        if(userInfoService.save(domain)){
            return Result.getInstance(ResultCode.SUCCESS.toString(), ResultMsg.SUCCESS,"","").getJson();
        }
        return Result.getInstance(ResultCode.ERROR.toString(), ResultMsg.ERROR,"","").getJson();
    }

    /**
     * 根据id删除实体类
     * 为了管理员易于操作支持批量操作
     * @param id
     * @return
     */
    @RequestMapping(value = "/user/{id}",method= RequestMethod.DELETE)
    public String delUserInfo(@PathVariable("id") String id) {
        loger.debug("/***根据用户id:{},删除实体类记录**/", id);
        String []ids=id.split(Constant.DHAO);
        if(id.split(Constant.DHAO).length>DEFAULT_ROW){
            return Result.getInstance(ResultCode.ERROR.toString(), ResultMsg.DEL_ERROR_IDS_TOO_MANY,"","").getJson();
        }
        Boolean flay=true;
        for(String did:ids){
            if(!userInfoService.delete(did)){
                flay=false;
            };
        }
        if(flay){
            return Result.getInstance(ResultCode.SUCCESS.toString(), ResultMsg.SUCCESS,"","").getJson();
        }
        return Result.getInstance(ResultCode.ERROR.toString(), ResultMsg.ERROR,"","").getJson();
    }
    /**
     * 更新实体类信息
     * @param domain
     * @return
     */
    @RequestMapping(value = "/user",method= RequestMethod.PUT)
    public String updateUserInfo(UserInfo domain) {
        loger.debug("/***更新实体类信息**/");
        if(userInfoService.update(domain)){
            return Result.getInstance(ResultCode.SUCCESS.toString(), ResultMsg.UPDATE_SUCCESS,"","").getJson();
        }
        return Result.getInstance(ResultCode.ERROR.toString(), ResultMsg.UPDATE_ERROR,"","").getJson();
    }


    /**
     * 根据id获取实体类信息
     * @param model
     * @param id 查询的id
     * @return
     */
    @RequestMapping(value = "/user/{id}",method= RequestMethod.GET)
    public String selectUserInfo(Model model, @PathVariable("id") String id) {
        loger.debug("/***根据用户id{},获取实体类基本信息**/", id);
        UserInfo userInfo= userInfoService.get(id);
        return Result.getInstance(ResultCode.SUCCESS.toString(), ResultMsg.SUCCESS,userInfo,"").getJson();
    }

    /**
     * 查询实体类列表,分页方法
     * @param userInfo
     * @return
     */

    @RequestMapping(value = "/users",method= RequestMethod.GET)
    public String selectUserInfoList(UserInfo userInfo,Pager pager) {
        loger.debug("/***分页查询方法,返回实体类列表**/");
        pager = new Pager(pager.getPage(), StrUtils.isBlank(pager.getRows())||Constant.NUMBER_0==pager.getRows()?DEFAULT_ROW:pager.getRows());
        Pager<UserInfo> userInfoPager= userInfoService.getPageList(userInfo, pager);
        return Result.getInstance(ResultCode.SUCCESS.toString(), ResultMsg.SUCCESS,userInfoPager,"").getJson();
    }



    @InitBinder
    public void initBinder(WebDataBinder binder) {
        /**
         * 第一种方式:使用WebDataBinder注册一个自定义的编辑器,编辑器是日期类型
         * 使用自定义的日期编辑器,日期格式:yyyy-MM-dd,第二个参数为是否为空  true代表可以为空
         *  yyyy-MM-dd hh:mm:ss
         */
        binder.registerCustomEditor(Date.class, new CustomDateEditor(
                new SimpleDateFormat("yyyy-MM-dd"), true));
    }


}

 

ServiceImpl层:参考DemoDomainServiceImpl类

Mapper一般都有现成的工具,所以根据公司用的插件生成即可(如下)

SpringBoot继承mybatis相对比较简单,

下载地址:https://github.com/shinians/limp-framework

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

十年呵护

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值