zoukankan      html  css  js  c++  java
  • springboot 使用 MyBatis 连接 mysql 数据库(2021.01.25)

    本文依照 (https://blog.csdn.net/dkbnull/article/details/87278817 Spring Boot整合MyBatis连接数据库) 的实践记录,主要实践MyBatis映射文件实现数据库的连接.

    备注:

    1. MyBatis查询数据库的方式有三种,xml文件查询复杂语句更好一些. https://www.cnblogs.com/thisiswhy/p/12909994.html
    2. 因为存在文件引用的原因,建议按照教程走完之后运行,中间可能存在引用文件还没有创建导致报错
    3. 如果连接数据库失败,请检查账号密码以及url前面的//斜杠数量是否正确,以及表名是否正确
    4. vscode搜索相关教程也可以实现运行springboot,自动导入包、自动生成get set等

    开发环境:

    • IDE:eclipse
    • jdk:15.0.1
    • Spring Boot:2.3.7.RELEASE
    • Maven:3.6.3
    • MySQL:8.0.18

    创建数据库:

      1.创建 spring_boot_blog 库

      2.创建表 admin 并写入一条数据

    CREATE TABLE `admin` (
     `id` int(11) NOT NULL AUTO_INCREMENT,
     `name` varchar(50) NOT NULL,
     PRIMARY KEY (`id`),
    ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci

    引入依赖:

    <dependencies>
        //pom.xml追加
        <dependencies>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            // mysql 8.+版本需要指定版本号
            <version>8.0.18</version>
        </dependency> 
    </dependencies>        

    MyBatis配置:

      1.在resources文件夹下新建mapper文件夹,用于存放MyBatis映射文件

      

      2.application.properties 增加MyBatis配置信息 (参考文章内是application.yml 增加MyBatis配置信息 )

    #https://blog.csdn.net/fu18838928050/article/details/105057704
    
    #mysql配置
    spring.datasource.url=jdbc:mysql://localhost:3306/spring_boot_blog?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT
    spring.datasource.username=root
    spring.datasource.password=root
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    server.tomcat.uri-encoding=UTF-8
    
    #MyBatis配置
    mybatis.mapper-locations=classpath:mapper/*.xml
    #这个地方写你model存放所在的包路径
    mybatis.type-aliases-package=com.example.demo.model

      2.在启动文件内增加注解@MapperScan("com.example.demo.dao"),括号内对应DAO层的包名

    package com.example.demo;
    
    import org.mybatis.spring.annotation.MapperScan;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    @MapperScan("com.example.demo.dao")
    public class DemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(DemoApplication.class, args);
        }
    
    }

    编写业务逻辑代码:

      1.在 com.example.demo 下创建 com.example.demo.mode 包并创建 TestModel 类

    package com.example.demo.model;
    
    public class TestModel {
    
        private int id;
        private String name;
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
    }

      2.在 com.example.demo 下创建 com.example.demo.dao包并创建 TestMapperV2 

    package com.example.demo.dao;
    
    import java.util.List;
    
    import com.example.demo.model.TestModel;
    import com.example.demo.model.*;
    public interface TestMapperV2 {
         List<TestModel> select();
         
         int insert(TestModel testModel);
    }

      3.在 com.example.demo 下创建 com.example.demo.service 包并创建 MySQLTestServiceV2 类

    package com.example.demo.service;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import com.example.demo.dao.TestMapperV2;
    import com.example.demo.model.TestModel;
    
    @Service
    public class MySQLTestServiceV2 {
        @Autowired
        private TestMapperV2 testMapperV2;  //这里会有报错,不用管
    
        public List<TestModel> select() {
            return testMapperV2.select();
        }
    
        public int insert(int id, String name) {
            TestModel testModel = new TestModel();
            testModel.setId(id);
            testModel.setName(name);
    
            return testMapperV2.insert(testModel);
        }
    }

      4.在 com.example.demo 下创建 com.example.demo.controller包并创建 MySQLTestControllerV2 

    package com.example.demo.controller;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.context.annotation.Scope;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    import com.example.demo.model.TestModel;
    import com.example.demo.service.MySQLTestServiceV2;
    
    @RestController
    @Scope("prototype")
    @RequestMapping("/mysql/test")
    public class MySQLTestControllerV2 {
        @Autowired
        private MySQLTestServiceV2 mySQLTestServiceV2;
    
        @PostMapping(value = "/selectV2")
        public List<TestModel> select() throws Exception {
            return mySQLTestServiceV2.select();
        }
    
        @PostMapping(value = "/insertV2")
        public int insert(@RequestParam(value = "id") int id,
                          @RequestParam(value = "name") String name) throws Exception {
            return mySQLTestServiceV2.insert(id, name);
        }
    }

      5.创建MyBatis映射文件,在 resources/mapper 下新建映射文件 TestMapper.xml,关于xml详细配置请看官方文档 https://mybatis.org/mybatis-3/zh/index.html

    <?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.example.demo.dao.TestMapperV2">
        <resultMap id="BaseResultMap" type="com.example.demo.model.TestModel">
            <id column="id" property="id" jdbcType="INTEGER"/>
            <result column="name" property="name" jdbcType="VARCHAR"/>
        </resultMap>
        <sql id="Base_Column_List">
            id, name
        </sql>
        <select id="select" resultMap="BaseResultMap">
            select
            <include refid="Base_Column_List"/>
            from admin
        </select>
        <insert id="insert" parameterType="com.example.demo.model.TestModel">
            insert into admin (id, name
            )
            values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}
            )
        </insert>
    </mapper>

    测试运行:

      Post 请求 localhost:8080/mysql/test/selectV2

      

    如果觉得文章对您有帮助,希望您能 关注+推荐 哦
  • 相关阅读:
    机器学习笔记之Boosting算法
    机器学习笔记之多重共线性问题以及如何解决
    机器学习笔记之在Visual Studio Code中使用Jupyter Notebook
    高数学习笔记之范数与距离度量(python实现)
    机器学习笔记之线性回归最小二乘法(公式推导和非调包实现)
    机器学习笔记之线性回归数学推导
    高数笔记之期望、方差与最小二乘法
    DataTable 去重 测试
    vs2019 项目历史记录
    sql 求和 语句
  • 原文地址:https://www.cnblogs.com/xiaqiuchu/p/14323182.html
Copyright © 2011-2022 走看看