【Mybatis工具(二)】SpringBoot整合Mybatis

最开始写这个笔记的时候已经有些年月了,当时使用的编辑器还是eclipse,springboot还不是那么流行。不得不承认的一点,就是作为一名程序员,你需要时刻保持学习!所以我们今天使用SpringBoot来整合Mybatis吧。

第一步:新建一个数据库
将下sql脚本导入到数据库中。

/*
Navicat MySQL Data Transfer

Source Server         : localhost_3306
Source Server Version : 50521
Source Host           : localhost:3306
Source Database       : mybatis

Target Server Type    : MYSQL
Target Server Version : 50521
File Encoding         : 65001

Date: 2015-04-09 16:03:53
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `orders`
-- ----------------------------
DROP TABLE IF EXISTS `orders`;
CREATE TABLE `orders` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL COMMENT '下单用户id',
  `number` varchar(32) NOT NULL COMMENT '订单号',
  `createtime` datetime NOT NULL COMMENT '创建订单时间',
  `note` varchar(100) DEFAULT NULL COMMENT '备注',
  PRIMARY KEY (`id`),
  KEY `FK_orders_1` (`user_id`),
  CONSTRAINT `FK_orders_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of orders
-- ----------------------------
INSERT INTO `orders` VALUES ('3', '1', '1000010', '2015-02-04 13:22:35', null);
INSERT INTO `orders` VALUES ('4', '1', '1000011', '2015-02-03 13:22:41', null);
INSERT INTO `orders` VALUES ('5', '10', '1000012', '2015-02-12 16:13:23', null);

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(32) NOT NULL COMMENT '用户名称',
  `birthday` date DEFAULT NULL COMMENT '生日',
  `sex` char(1) DEFAULT NULL COMMENT '性别',
  `address` varchar(256) DEFAULT NULL COMMENT '地址',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', '王五', null, '2', null);
INSERT INTO `user` VALUES ('10', '张三', '2014-07-10', '1', '北京市');
INSERT INTO `user` VALUES ('16', '张小明', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('22', '陈小明', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('24', '张三丰', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('25', '陈小明', null, '1', '河南郑州');
INSERT INTO `user` VALUES ('26', '王五', null, null, null);

第二步:创建一个Maven项目
这个不说了

第三步:导入依赖
不卖关子,直接奉上

<?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>com.dong</groupId>
    <artifactId>mybatis-review</artifactId>
    <version>1.0-SNAPSHOT</version>


    <!--    springboot 父项目-->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
    </parent>

    <dependencies>
        <!--        springboot 启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!--        springboot test 启动器-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--        spring web启动器-->
        <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.3.4.RELEASE</version>
        </dependency>
        <!--        lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
        <!--        mysql jdbc驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>


</project>

第四步:配置文件

如图创建文件,并复制以下内容

# 数据库连接池
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus_test?useSSL=false&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root

# 日志文件
logging.level.root=warn
logging.level.com.fang.dao=trace
logging.pattern.console='%p%m%n'

都很简单,不多赘述

第五步:架构

如图所示,创建包和类

第六步:创建Mapper

规范如下

<?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">

第七步:编码
主要讲解的就是Mybatis部分的代码

  1. 在application.properties中进行全局配置
#mybatis
mybatis.mapper-locations=classpath:mapper/UserMapper.xml
mybatis.type-aliases-package=com.tyust.entity

第一行代码的意思是mapper的位置,第二行是别名的设置
2. Application类的全局设置

@SpringBootApplication
@MapperScan("com.tyust.dao")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

注解@MapperScan("com.tyust.dao")会告诉电脑mapper接口的位置。
通过这两步的设置,springboot就可以将mapper和xml进行映射,这和我们之前说过的xml中的mapping映射是一样的,但是可以感受到方便多了。

  1. 我们应该在UserMapper接口中声明一种方法
public User queryUserById(int id);
  1. 在UserMapper.xml中完成他的sql
<mapper namespace="com.tyust.dao.UserMapper">

    <!-- 通用查询结果列-->
    <select id="queryUserById" parameterType="int" resultType="User">
         select *
         from user
         where ID = #{id}
    </select>

</mapper>

namespace是将UserMapper类和UserMapper.xml进行一对一的联系。返回值是User而不是com.tyust.entity.User,就是别名的作用。

至此mybatis就算是配置好了。

  1. 其他

service层

@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    public User showUserInfo(int id) {
        return userMapper.queryUserById(id);
    }
}

controller层

@RestController
public class UserController {

    @Autowired
    UserService userService;

    @ResponseBody
    @GetMapping(value = "/user/{id}")
    public User showUserInfo(@PathVariable int id) {
        return userService.showUserInfo(id);
    }
}
  1. 运行

http://localhost:8080/user/1

通过接口访问,即可返回json字符串

posted @ 2020-10-20 17:53  朱李洛克  阅读(84)  评论(0编辑  收藏  举报
// 侧边栏目录 // https://blog-static.cnblogs.com/files/douzujun/marvin.nav.my1502.css