使用springBoot整合mybatis plus,并且用postman向本地数据库查询出一条数据

1.首先,准备阶段,用ideal创建一个springBoot的web项目,并且能够向浏览器端输出hello world,
这里我之前文章有讲述,这里就不在叙述。
2.向已准备好的web项目的pom.xml文件添加以下依赖:


            mysql
            mysql-connector-java
            8.0.19
        
        
        
            com.baomidou
            mybatis-plus
            ${mybatisplus.version}
        
        
            com.baomidou
            mybatisplus-spring-boot-starter
            ${mybatisplus.spring.boot.version}
        
        
            com.alibaba
            druid-spring-boot-starter
            ${druid.version}
        

我个人的完整pom.xml文件如下



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.5.RELEASE
         
    
    com.tefei
    isak
    0.0.1-SNAPSHOT
    isak
    Demo project for Spring Boot

    
        1.8
        2.1.9
        1.0.5
        1.1.10
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
            
                
                    org.junit.vintage
                    junit-vintage-engine
                
            
        
        
        
        
        
            mysql
            mysql-connector-java
            8.0.19
        
        
        
            com.baomidou
            mybatis-plus
            ${mybatisplus.version}
        
        
            com.baomidou
            mybatisplus-spring-boot-starter
            ${mybatisplus.spring.boot.version}
        
        
            com.alibaba
            druid-spring-boot-starter
            ${druid.version}
        
        
            io.swagger
            swagger-annotations
            1.5.13
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


在以上依赖中,注意,我的mysql驱动依赖版本是8.0.19(因为我本地的mysql版本是8.0,我网上搜了一下对应的驱动版本,发现8.0对应的驱动版本为8.0.19,版本不一,可能还有其它对应的版本,自行对自己的本地mysql的版本添加对应的驱动即可)

3.添加完依赖后,运行项目,发现项目会报一个与url相关的错误,意思大概是你没有配置数据库连接路径,错误如下:

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

要解决该错误,向项目的配置文件添加以下代码即可:

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driverClassName: com.mysql.cj.jdbc.Driver
    druid:
      url: jdbc:mysql://localhost:3306/yz_server?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT
      username: root
      password: 1234

以上代码的url要换成自己本地的数据库连接,还有username和password要填写正确。
我个人完整的配置文件如下:

server:
  port: 8081
  servlet:
    context-path: /isak
spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driverClassName: com.mysql.cj.jdbc.Driver
    druid:
      url: jdbc:mysql://localhost:3306/yz_server?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT
      username: root
      password: 1234
#mybatis
mybatis-plus:
  mapper-locations: classpath:mapper/**/*.xml
  #实体扫描,多个package用逗号或者分号分隔
  typeAliasesPackage: com.tefei.*.entity
  global-config:
    #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
    id-type: 0
    #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
    field-strategy: 1
    #驼峰下划线转换
    db-column-underline: true
    #刷新mapper 调试神器
    refresh-mapper: true
    #数据库大写下划线转换
    #capital-mode: true
    # Sequence序列接口实现类配置
    #key-generator: com.baomidou.mybatisplus.incrementer.OracleKeyGenerator
    #逻辑删除配置
    logic-delete-value: -1
    logic-not-delete-value: 0
    #自定义填充策略接口实现
    #meta-object-handler: com.baomidou.springboot.xxx
    #自定义SQL注入器
    sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false
    call-setters-on-nulls: true
#    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

在以上配置都准备完后(项目能够正常运行),就可以开始编写dao、entity、service、mapper和controller了。
个人entity层代码如下:

package com.tefei.isak.entity;
import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.annotations.TableId;
import com.baomidou.mybatisplus.annotations.TableName;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Date;

/**
 * @author isak
 * @date 2020-03-14 20:16
 */
@TableName("user_detail")
@ApiModel(value = "用户对象")
public class UserDetailEntity implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     *
     */
    @TableId
    private Long id;
    /**
     *
     */
    private String openid;
    /**
     *
     */
    @ApiModelProperty(value = "用户头像")
    private String headimg;
    /**
     *
     */
    @ApiModelProperty(value = "用户昵称")
    private String name;

    /**
     * 性别
     */
    private boolean gender;

    /**
     *
     */
    private String city;
    /**
     *
     */
    private String province;

    private String region;

    /**
     *
     */
    private String address;
    /**
     *
     */
    private String remark;


    private String userCode;
    /**
     *
     */
    private String lgpoint;
    private String phone;
    private String trueName;
    @ApiModelProperty(value = "个人介绍")
    private String introduce;
    /**
     *
     */
    private Date createTime;
    /**
     *
     */
    private Date updateTime;


    @TableField(exist = false)
    private long countOrder;
    @TableField(exist = false)
    private Double sumEarnings;


    private boolean isVip;
    @TableField(exist = false)
    private Long inviteCount;

    private Long level;


    /**
     * 设置:
     */
    public void setId(Long id) {
        this.id = id;
    }

    /**
     * 获取:
     */
    public Long getId() {
        return id;
    }

    /**
     * 设置:
     */
    public void setOpenid(String openid) {
        this.openid = openid;
    }

    /**
     * 获取:
     */
    public String getOpenid() {
        return openid;
    }

    /**
     * 设置:
     */
    public void setHeadimg(String headimg) {
        this.headimg = headimg;
    }

    /**
     * 获取:
     */
    public String getHeadimg() {
        return headimg;
    }

    /**
     * 设置:
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * 获取:
     */
    public String getName() {
        return name;
    }

    /**
     * 设置:
     */
    public void setAddress(String address) {
        this.address = address;
    }

    /**
     * 获取:
     */
    public String getAddress() {
        return address;
    }

    /**
     * 设置:
     */
    public void setRemark(String remark) {
        this.remark = remark;
    }

    /**
     * 获取:
     */
    public String getRemark() {
        return remark;
    }

    /**
     * 设置:
     */
    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    /**
     * 获取:
     */
    public Date getCreateTime() {
        return createTime;
    }

    /**
     * 设置:
     */
    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    /**
     * 获取:
     */
    public Date getUpdateTime() {
        return updateTime;
    }

    public String getUserCode() {
        return userCode;
    }

    public void setUserCode(String userCode) {
        this.userCode = userCode;
    }

    public String getLgpoint() {
        return lgpoint;
    }

    public void setLgpoint(String lgpoint) {
        this.lgpoint = lgpoint;
    }


    public boolean isGender() {
        return gender;
    }

    public void setGender(boolean gender) {
        this.gender = gender;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getTrueName() {
        return trueName;
    }

    public void setTrueName(String trueName) {
        this.trueName = trueName;
    }

    public long getCountOrder() {
        return countOrder;
    }

    public void setCountOrder(long countOrder) {
        this.countOrder = countOrder;
    }

    public Double getSumEarnings() {
        return sumEarnings;
    }

    public void setSumEarnings(Double sumEarnings) {
        this.sumEarnings = sumEarnings;
    }

    public boolean isVip() {
        return isVip;
    }

    public void setVip(boolean vip) {
        isVip = vip;
    }

    public Long getInviteCount() {
        return inviteCount;
    }

    public void setInviteCount(Long inviteCount) {
        this.inviteCount = inviteCount;
    }

    public String getRegion() {
        return region;
    }

    public void setRegion(String region) {
        this.region = region;
    }

    public String getIntroduce() {
        return introduce;
    }

    public void setIntroduce(String introduce) {
        this.introduce = introduce;
    }

    public Long getLevel() {
        return level;
    }

    public void setLevel(Long level) {
        this.level = level;
    }
}

以上实体的属性和本地数据库里面的user_detail表的字段相对应。
然后是:dao层代码如下:

package com.tefei.isak.dao;

import com.baomidou.mybatisplus.mapper.BaseMapper;
import com.tefei.isak.entity.UserDetailEntity;
/**
 * @author isak
 * @date 2020-03-14 20:16
 */
public interface UserDetailDao extends BaseMapper {

}

该层代码比较简单,只要继承了mybatisplus的BaseMapper即可。
再然后,是书写mapper,如下:






    
    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    

    
    

编写mapper的时候要注意:namespace和type必须对应上面的dao和entity,另外,如果自己书写了sql查询语句的话,resultType也必须和指定entity对应。
接下来就是service和controller了
关于service和serviceImp的代码如下:

package com.tefei.isak.service;

import com.baomidou.mybatisplus.service.IService;
import com.tefei.isak.entity.UserDetailEntity;

/**
 * @author isak
 * @date 2020-03-14 20:16
 */
public interface UserDetailService extends IService {

}
package com.tefei.isak.service.serviceImp;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.tefei.isak.dao.UserDetailDao;
import com.tefei.isak.entity.UserDetailEntity;
import com.tefei.isak.service.UserDetailService;
import org.springframework.stereotype.Service;



@Service("userDetailService")
public class UserDetailServiceImpl extends ServiceImpl implements UserDetailService {

}

最后,再编写一个controller来调用service的服务就好了,这里说明一下,mybats plus 已经为我们封装好了基本的CRUD了,我们可以直接进行基本的增删改查啦。
controller层代码如下:

package com.tefei.isak.controller;

import com.tefei.isak.common.R;
import com.tefei.isak.entity.UserDetailEntity;
import com.tefei.isak.service.UserDetailService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;




/**
 * @author isak
 * @date 2020-03-14 20:16
 */
@RestController
@RequestMapping("userdetail")
@Api(tags = "用户接口")
public class UserDetailController {

    @Autowired
    private UserDetailService userDetailService;
    @RequestMapping("/info/{id}")
    public R queryById(@PathVariable("id") Long id){
        UserDetailEntity userDetailEntity = userDetailService.selectById(id);
        if(userDetailEntity!=null){
            return R.ok().put("userDetailEntity",userDetailEntity);
        }else{
         return R.error("查詢错误");
        }
    }

}

上面的selectById方法就是mybatis plus为我们封装好的方法(通过主键id查询数据)。
还有就是这个controller层的R对象你可能有不理解的地方。其实这个R对象就是对这个方法的返回数据进行封装,先看返回的数据效果吧,我用postman对controller的接口进行请求,效果如下:


1.PNG

返回的数据格式:

{
    "msg": "success",
    "code": 0,
    "userDetailEntity": {
        "id": 13,
        "openid": "oI1hhw07KPweExgvGo9f713GOzgc",
        "headimg": "http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLxxZWshOd9XZBjRYnwgLTjAkmHnDyJN08RA2OIG4qicd5DScXdsyzfFb0QCLQhktK0ug791ryEjUg/132",
        "name": "Xiongfan",
        "gender": true,
        "city": "九江",
        "province": "江西",
        "region": null,
        "address": null,
        "remark": null,
        "userCode": "10013",
        "lgpoint": null,
        "phone": null,
        "trueName": "Xiongfan",
        "introduce": null,
        "createTime": "2019-12-06T12:05:15.000+0000",
        "updateTime": "2019-12-06T12:05:15.000+0000",
        "countOrder": 0,
        "sumEarnings": null,
        "inviteCount": null,
        "level": 1,
        "vip": false
    }
}

如果你不熟悉这个R对象的话,我们对controller进行改进:改进的代码如下(修改方法返回对象)

package com.tefei.isak.controller;

import com.tefei.isak.common.R;
import com.tefei.isak.entity.UserDetailEntity;
import com.tefei.isak.service.UserDetailService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;




/**
 * @author isak
 * @date 2020-03-14 20:16
 */
@RestController
@RequestMapping("userdetail")
@Api(tags = "用户接口")
public class UserDetailController {

    @Autowired
    private UserDetailService userDetailService;
    @RequestMapping("/info/{id}")
    public UserDetailEntity queryById(@PathVariable("id") Long id){
        UserDetailEntity userDetailEntity = userDetailService.selectById(id);
        if(userDetailEntity!=null){
            return userDetailEntity;
        }else{
         return null;
        }
    }

}

然后再用postman进行模拟,效果如下:


1.PNG

返回的数据格式

{
    "id": 13,
    "openid": "oI1hhw07KPweExgvGo9f713GOzgc",
    "headimg": "http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTLxxZWshOd9XZBjRYnwgLTjAkmHnDyJN08RA2OIG4qicd5DScXdsyzfFb0QCLQhktK0ug791ryEjUg/132",
    "name": "Xiongfan",
    "gender": true,
    "city": "九江",
    "province": "江西",
    "region": null,
    "address": null,
    "remark": null,
    "userCode": "10013",
    "lgpoint": null,
    "phone": null,
    "trueName": "Xiongfan",
    "introduce": null,
    "createTime": "2019-12-06T12:05:15.000+0000",
    "updateTime": "2019-12-06T12:05:15.000+0000",
    "countOrder": 0,
    "sumEarnings": null,
    "inviteCount": null,
    "level": 1,
    "vip": false
}

由此可见,关于这个R对象,只是把请求的数据以不同形式进行返回。
自此,一个关于springBoot的web项目简单整合mybatis plus就完毕啦。
补充:
所查询的数据在数据库中如下图所示:


1.PNG

ps:加上俺的项目目录结构截图,方便理解


1.PNG

(天啦撸,这个整合我弄了好几次,一直失败,这次终于成功了,赶紧写个总结一下,万一哪天忘了 = _ =)
每天进步一点点,学习很重要,但感觉总结更重要啊!!!

你可能感兴趣的:(使用springBoot整合mybatis plus,并且用postman向本地数据库查询出一条数据)