首页 > 其他分享 >SpringBoot整合MyBatis

SpringBoot整合MyBatis

时间:2023-01-23 17:11:37浏览次数:68  
标签:SpringBoot demo qzcsbj 整合 MyBatis import com public user

 

添加pom依赖

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
            <scope>provided</scope>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.0</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

  

准备数据库

SET FOREIGN_KEY_CHECKS=0;
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL COMMENT '用户名',
  `password` varchar(255) NOT NULL COMMENT '密码',
  `real_name` varchar(255) NOT NULL COMMENT '真实名',
  `sex` varchar(255) DEFAULT NULL COMMENT '性别',
  `birthday` date DEFAULT NULL COMMENT '生日',
  `phone` varchar(255) NOT NULL COMMENT '电话',
  `utype` tinyint(1) DEFAULT NULL COMMENT '用户类型',
  `addtime` datetime DEFAULT NULL COMMENT '添加时间',
  `adduser` varchar(255) DEFAULT NULL COMMENT '添加者',
  PRIMARY KEY (`id`),
  UNIQUE KEY `phone` (`phone`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
      
insert into `user` values(1,'qzcsbj1','62f7f5673e94eca261b8fce7ae7863a4','qzcsbj1','男','2018-09-06','13800000001',0,now(),'qzcsbj');
insert into `user` values(2,'qzcsbj2','62f7f5673e94eca261b8fce7ae7863a4','qzcsbj2','女','2018-09-07','13800000002',1,now(),'qzcsbj');
insert into `user` values(3,'qzcsbj3','62f7f5673e94eca261b8fce7ae7863a4','qzcsbj3','男','2018-09-08','13800000003',0,now(),'qzcsbj');
insert into `user` values(4,'qzcsbj4','62f7f5673e94eca261b8fce7ae7863a4','qzcsbj4','女','2018-09-09','13800000004',1,now(),'qzcsbj');
insert into `user` values(5,'qzcsbj5','62f7f5673e94eca261b8fce7ae7863a4','qzcsbj5','女','2018-09-10','13800000005',0,now(),'qzcsbj');

 

创建实体类

package com.qzcsbj.demo.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Date;

/**
 * @公众号 : 全栈测试笔记
 * @博客 : www.cnblogs.com/uncleyong
 * @微信 : ren168632201
 * @描述 : <>
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Serializable {
    private static final long serialVersionUID = 5753660691492463802L;

    private Integer id;  // 实体类推荐用包装类
    private String username;
    private String password;
    private String realName;
    private String sex;
    private Date birthday;
    private String phone;
    private String utype;
    private String addtime;
    private String adduser;
}

 

添加jdbc、MyBatis参数配置

application-test.properties

# 测试环境
server.port=8082

# 数据库的连接信息
spring.datasource.url=jdbc:mysql://192.168.117.180:3306/gift?useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=root
spring.datasource.password=qzcsbj
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource


# MyBatis参数配置
# 1、指定Mapper.xml的位置
mybatis.mapper-locations=classpath:mappers/*.xml
# 2、取别名
mybatis.type-aliases-package=com.qzcsbj.demo.pojo

  

application.properties

spring.profiles.active=test

 

创建mapper层接口及xml文件

mapper下创建UserMapper

package com.qzcsbj.demo.mapper;

import com.qzcsbj.demo.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;

/**
 * @公众号 : 全栈测试笔记
 * @博客 : www.cnblogs.com/uncleyong
 * @微信 : ren168632201
 * @描述 : <>
 */
@Mapper
public interface UserMapper {
    public List<User> getUsers();
}

 

resources下创建mappers目录,此目录下创建UserMapper.xml文件

 

<?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="com.qzcsbj.demo.mapper.UserMapper">
    <select id="getUsers" resultType="User">
        select * from user
    </select>
</mapper>

  

测试

我们这里只是演示结果,直接在控制层测试(springboot标准的单元测试,参考:https://www.cnblogs.com/uncleyong/p/17065297.html

UserController

package com.qzcsbj.demo.controller;

import com.qzcsbj.demo.mapper.UserMapper;
import com.qzcsbj.demo.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @公众号 : 全栈测试笔记
 * @博客 : www.cnblogs.com/uncleyong
 * @微信 : ren168632201
 * @描述 : <>
 */
@RestController
@RequestMapping("/user")
public class UserController {
    // @Autowired
    @Resource
    UserMapper userMapper;

    @RequestMapping("/getall")
    public List<User> getUsers(){
        System.out.println("======获取所有用户");
        return userMapper.getUsers();
    }
}

 

请求:localhost:8082/user/getall

安装了JSON Viewer,谷歌浏览器效果是:

 

上面有个问题,就是realName是null,因为实体类属性名和数据库表字段名不一样,

修改UserMapper.xml

<?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="com.qzcsbj.demo.mapper.UserMapper">
    <resultMap id="userMap" type="com.qzcsbj.demo.pojo.User">
        <id column="id" property="id"/>
        <result column="real_name" property="realName"/>
    </resultMap>
    <select id="getUsers" resultMap="userMap">
        select * from user
    </select>
</mapper>

 

重启项目后再次访问:localhost:8082/user/getall

 

加一个添加用户的接口

mapper接口

package com.qzcsbj.demo.mapper;

import com.qzcsbj.demo.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;

/**
 * @公众号 : 全栈测试笔记
 * @博客 : www.cnblogs.com/uncleyong
 * @微信 : ren168632201
 * @描述 : <>
 */
@Mapper
public interface UserMapper {
    public List<User> getUsers();
    public int addUser(User user);
}

  

xml映射文件

<?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="com.qzcsbj.demo.mapper.UserMapper">
    <resultMap id="userMap" type="com.qzcsbj.demo.pojo.User">
        <id column="id" property="id"/>
        <result column="real_name" property="realName"/>
    </resultMap>
    <select id="getUsers" resultMap="userMap">
        select * from user
    </select>

    <insert id="addUser" parameterType="User">
insert into user values(null,#{username},#{password},#{realName},#{sex},#{birthday},#{phone},#{utype},now(),#{adduser})
</insert>
</mapper>

  

service层接口

package com.qzcsbj.demo.service;

import com.qzcsbj.demo.pojo.User;

import java.util.List;

/**
 * @公众号 : 全栈测试笔记
 * @博客 : www.cnblogs.com/uncleyong
 * @微信 : ren168632201
 * @描述 : <>
 */
public interface UserService {
    public List<User> getUsers();
    public int addUser(User user);
}

  

service实现类

package com.qzcsbj.demo.service.impl;

import com.qzcsbj.demo.mapper.UserMapper;
import com.qzcsbj.demo.pojo.User;
import com.qzcsbj.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @公众号 : 全栈测试笔记
 * @博客 : www.cnblogs.com/uncleyong
 * @微信 : ren168632201
 * @描述 : <>
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public List<User> getUsers() {
        return userMapper.getUsers();
    }

    @Override
    public int addUser(User user) {
        return userMapper.addUser(user);
    }
}

  

控制层

package com.qzcsbj.demo.controller;

import com.qzcsbj.demo.commons.ResultCode;
import com.qzcsbj.demo.commons.ResultCommon;
import com.qzcsbj.demo.mapper.UserMapper;
import com.qzcsbj.demo.pojo.User;
import com.qzcsbj.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @公众号 : 全栈测试笔记
 * @博客 : www.cnblogs.com/uncleyong
 * @微信 : ren168632201
 * @描述 : <>
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;

    // 查询所有
    @RequestMapping("/getall")
    public ResultCommon getUsers(){
        System.out.println("======获取所有用户");
        List<User> users = userService.getUsers();
        return ResultCommon.success(ResultCode.SUCCESS,users);
    }

    // 新增
    @PostMapping("/adduser")
    public ResultCommon addUser(User user){
        System.out.println("======添加用户");
        int count = userService.addUser(user);
        if (count>0){
            return ResultCommon.success(ResultCode.SUCCESS);
        } else {
            return ResultCommon.fail(ResultCode.FAIL);
        }
    }
}

 

jmeter请求添加用户接口

发送表单

 

结果

数据库

 

发送json

控制器新增如下内容

    // 新增
    @PostMapping("/adduser2")
    public ResultCommon addUser2(@RequestBody User user){
        System.out.println("======添加用户:" + user);
        int count = userService.addUser(user);
        if (count>0){
            return ResultCommon.success(ResultCode.SUCCESS);
        } else {
            return ResultCommon.fail(ResultCode.FAIL);
        }
    }

 

 jmeter脚本添加信息头

 

请求体

{
	"username":"qzcsbj10",
	"password":"123456",
	"realName":"qzcsbj10",
	"sex":"女",
	"birthday":"2011-01-01",
	"phone":"13800000010",
	"utype":"1",
	"adduser":"qzcsbj"
}

 

因为请求体有中文,内容编码填上utf8

 

结果

 

数据库

 

【bak】

原文会持续更新,原文地址:https://www.cnblogs.com/uncleyong/p/17065293.html

 

标签:SpringBoot,demo,qzcsbj,整合,MyBatis,import,com,public,user
From: https://www.cnblogs.com/uncleyong/p/17065293.html

相关文章

  • SpringBoot集成JWT实现token验证
    一、简介Jwt全称是:jsonwebtoken。它将用户信息加密到token里,服务器不保存任何用户信息。服务器通过使用保存的密钥验证token的正确性,只要正确即通过验证。优点简洁......
  • 【SpringBoot】源码之 Java16新特性:【instanceOf】
    在java16之前,我们要进行instanceOf判断一般会伴随着强转操作,就像这样:if(objinstanceofString){Strings=(String)obj;...}这样的书写方式看起来比......
  • 230122_50_SpringBoot入门
    SpringBootWeb开发jar:webapp!自动装配1.创建应用,选择模块springboot到底帮我们配置了什么?我们能不能进行修改?能修改哪些东西?能不能扩展?xxxAutoConfiguration..向容......
  • 学习笔记——SSM整合(思路、步骤)
    2023-01-22一、SSM整合1、Spring+SpringMVC(1)容器管理对象,由DispatcherServlet管理(2)Spring容器对象,由ContextLoaderListener管理2、解决组件扫描的冲突问题(1)SpringM......
  • springboot的原理
    SpringBoot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程,该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板......
  • SpringBoot配置文件详解
    简介SpringBoot全局配置文件默认为src/main/resources下的application.properties,后缀可以改为yml,如果application.yml和application.properties两个配置文件都存在,那么,p......
  • Docker 部署 SpringBoot 项目
    Dockerfilehouse.jar为jar包名称/data为存放路径FROMlpicanco/java11-alpineMAINTAINERchenglong<long7@vip.qq.com>VOLUME/tmpRUNmkdir/dataEXPOS......
  • Mybatis全方位深入源码剖析
    文章目录MyBatis源码剖析​​1MyBatis框架概述​​​​2JDBC缺陷总结​​​​3MyBatis快速入门​​​​3.1搭建Mybatis开发环境​​​​2.2.1创建Mave......
  • 【转】SpringBoot的44种启动器
    springBoot应用启动器基本的一共有44种,具体如下:1)spring-boot-starter这是SpringBoot的核心启动器,包含了自动配置、日志和YAML。2)spring-boot-starter-actuator帮助监控......
  • 【问题记录】【Mybatis-Plus】saveBatch MybatisPlusException: Error: Cannot execut
    1 问题描述MyBatis-Plus版本<mybatis-plus-boot-starter.version>3.3.0</mybatis-plus-boot-starter.version>由于Mybatis-Plus本身已经有增删改查以及批量保存的基本......