准备

1.安装IDEA
2.安装JDK
3.安装mysql
4.配置Mean仓库

创建springboot项目

  1. 打开IDEA,点击File–>New—>Project
  2. springboot配置mysql驱动properties springboot怎么配置mybatis_mybatis


  3. 修改图中三处即可,点击下一步
  4. springboot配置mysql驱动properties springboot怎么配置mybatis_spring boot_02

  5.  
  6. 添加项目依赖,此处添加三个依赖,Web,Mysql ,Mybatis。(也可不选,等项目创建完后,再往pom.xml里添加相应的依赖即可。点击next。
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.30</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.3</version>
        </dependency>
  1. 确定项目名,点击finish,如果弹出第二张图的选项,选择OK,创建相应的文件夹。
  2. springboot配置mysql驱动properties springboot怎么配置mybatis_mybatis_03


  3. 对Maven仓库进行配置。点击左上角的File,选择菜单里的Settings选项。可直接搜索Maven,直接点击,不用打开子目录。右边即会展示如图配置项Maven仓库的默认配置都是在C盘的用户目录下,建议更换位置。勾选图中圈出的Override,再点击旁边的文件夹,就能对配置文件的位置进行修改了。
    建议先行创建文件夹,在D盘创建了一个Maven文件夹,并将配置文件settings.xml(下文有代码)放于该目录下,并在该目录下(与settings.xml同级)创建文件夹repository(以后的依赖都会存放于此),点🆗。
  4. springboot配置mysql驱动properties springboot怎么配置mybatis_xml_04

  5. settings.xml的代码:
<?xml version="1.0" encoding="UTF-8"?>

<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
-->

<!--
 | This is the configuration file for Maven. It can be specified at two levels:
 |
 |  1. User Level. This settings.xml file provides configuration for a single user,
 |                 and is normally provided in ${user.home}/.m2/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -s /path/to/user/settings.xml
 |
 |  2. Global Level. This settings.xml file provides configuration for all Maven
 |                 users on a machine (assuming they're all using the same Maven
 |                 installation). It's normally provided in
 |                 ${maven.home}/conf/settings.xml.
 |
 |                 NOTE: This location can be overridden with the CLI option:
 |
 |                 -gs /path/to/global/settings.xml
 |
 | The sections in this sample file are intended to give you a running start at
 | getting the most out of your Maven installation. Where appropriate, the default
 | values (values used when the setting is not specified) are provided.
 |
 |-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ${user.home}/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->

  <!-- interactiveMode
   | This will determine whether maven prompts you when it needs input. If set to false,
   | maven will use a sensible default value, perhaps based on some other setting, for
   | the parameter in question.
   |
   | Default: true
  <interactiveMode>true</interactiveMode>
  -->

  <!-- offline
   | Determines whether maven should attempt to connect to the network when executing a build.
   | This will have an effect on artifact downloads, artifact deployment, and others.
   |
   | Default: false
  <offline>false</offline>
  -->

  <!-- pluginGroups
   | This is a list of additional group identifiers that will be searched when resolving plugins by their prefix, i.e.
   | when invoking a command line like "mvn prefix:goal". Maven will automatically add the group identifiers
   | "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not already contained in the list.
   |-->
  <pluginGroups>
    <!-- pluginGroup
     | Specifies a further group identifier to use for plugin lookup.
    <pluginGroup>com.your.plugins</pluginGroup>
    -->
  </pluginGroups>

  <!-- proxies
   | This is a list of proxies which can be used on this machine to connect to the network.
   | Unless otherwise specified (by system property or command-line switch), the first proxy
   | specification in this list marked as active will be used.
   |-->
  <proxies>
    <!-- proxy
     | Specification for one proxy, to be used in connecting to the network.
     |
    <proxy>
      <id>optional</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>proxyuser</username>
      <password>proxypass</password>
      <host>proxy.host.net</host>
      <port>80</port>
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts>
    </proxy>
    -->
  </proxies>

  <!-- servers
   | This is a list of authentication profiles, keyed by the server-id used within the system.
   | Authentication profiles can be used whenever maven must make a connection to a remote server.
   |-->
  <servers>
    <!-- server
     | Specifies the authentication information to use when connecting to a particular server, identified by
     | a unique name within the system (referred to by the 'id' attribute below).
     |
     | NOTE: You should either specify username/password OR privateKey/passphrase, since these pairings are
     |       used together.
     |
    <server>
      <id>deploymentRepo</id>
      <username>repouser</username>
      <password>repopwd</password>
    </server>
    -->

    <!-- Another sample, using keys to authenticate.
    <server>
      <id>siteServer</id>
      <privateKey>/path/to/private/key</privateKey>
      <passphrase>optional; leave empty if not used.</passphrase>
    </server>
    -->
  </servers>

  <!-- mirrors
   | This is a list of mirrors to be used in downloading artifacts from remote repositories.
   |
   | It works like this: a POM may declare a repository to use in resolving certain artifacts.
   | However, this repository may have problems with heavy traffic at times, so people have mirrored
   | it to several places.
   |
   | That repository definition will have a unique id, so we can create a mirror reference for that
   | repository, to be used as an alternate download site. The mirror site will be the preferred
   | server for that repository.
   |-->
  <mirrors>

  	<mirror>
      <id>alimaven</id>
      <name>aliyun maven</name>
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
      <mirrorOf>central</mirrorOf>
    </mirror>
    <!-- mirror
     | Specifies a repository mirror site to use instead of a given repository. The repository that
     | this mirror serves has an ID that matches the mirrorOf element of this mirror. IDs are used
     | for inheritance and direct lookup purposes, and must be unique across the set of mirrors.
     |
    <mirror>
      <id>mirrorId</id>
      <mirrorOf>repositoryId</mirrorOf>
      <name>Human Readable Name for this Mirror.</name>
      <url>http://my.repository.com/repo/path</url>
    </mirror>
     -->
  </mirrors>

  <!-- profiles
   | This is a list of profiles which can be activated in a variety of ways, and which can modify
   | the build process. Profiles provided in the settings.xml are intended to provide local machine-
   | specific paths and repository locations which allow the build to work in the local environment.
   |
   | For example, if you have an integration testing plugin - like cactus - that needs to know where
   | your Tomcat instance is installed, you can provide a variable here such that the variable is
   | dereferenced during the build process to configure the cactus plugin.
   |
   | As noted above, profiles can be activated in a variety of ways. One way - the activeProfiles
   | section of this document (settings.xml) - will be discussed later. Another way essentially
   | relies on the detection of a system property, either matching a particular value for the property,
   | or merely testing its existence. Profiles can also be activated by JDK version prefix, where a
   | value of '1.4' might activate a profile when the build is executed on a JDK version of '1.4.2_07'.
   | Finally, the list of active profiles can be specified directly from the command line.
   |
   | NOTE: For profiles defined in the settings.xml, you are restricted to specifying only artifact
   |       repositories, plugin repositories, and free-form properties to be used as configuration
   |       variables for plugins in the POM.
   |
   |-->
  <profiles>
    <!-- profile
     | Specifies a set of introductions to the build process, to be activated using one or more of the
     | mechanisms described above. For inheritance purposes, and to activate profiles via <activatedProfiles/>
     | or the command line, profiles have to have an ID that is unique.
     |
     | An encouraged best practice for profile identification is to use a consistent naming convention
     | for profiles, such as 'env-dev', 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc.
     | This will make it more intuitive to understand what the set of introduced profiles is attempting
     | to accomplish, particularly when you only have a list of profile id's for debug.
     |
     | This profile example uses the JDK version to trigger activation, and provides a JDK-specific repo.
    <profile>
      <id>jdk-1.4</id>

      <activation>
        <jdk>1.4</jdk>
      </activation>

      <repositories>
        <repository>
          <id>jdk14</id>
          <name>Repository for JDK 1.4 builds</name>
          <url>http://www.myhost.com/maven/jdk14</url>
          <layout>default</layout>
          <snapshotPolicy>always</snapshotPolicy>
        </repository>
      </repositories>
    </profile>
    -->

    <!--
     | Here is another profile, activated by the system property 'target-env' with a value of 'dev',
     | which provides a specific path to the Tomcat instance. To use this, your plugin configuration
     | might hypothetically look like:
     |
     | ...
     | <plugin>
     |   <groupId>org.myco.myplugins</groupId>
     |   <artifactId>myplugin</artifactId>
     |
     |   <configuration>
     |     <tomcatLocation>${tomcatPath}</tomcatLocation>
     |   </configuration>
     | </plugin>
     | ...
     |
     | NOTE: If you just wanted to inject this configuration whenever someone set 'target-env' to
     |       anything, you could just leave off the <value/> inside the activation-property.
     |
    <profile>
      <id>env-dev</id>

      <activation>
        <property>
          <name>target-env</name>
          <value>dev</value>
        </property>
      </activation>

      <properties>
        <tomcatPath>/path/to/tomcat/instance</tomcatPath>
      </properties>
    </profile>
    -->
  </profiles>

  <!-- activeProfiles
   | List of profiles that are active for all builds.
   |
  <activeProfiles>
    <activeProfile>alwaysActiveProfile</activeProfile>
    <activeProfile>anotherAlwaysActiveProfile</activeProfile>
  </activeProfiles>
  -->
</settings>

springboot配置mysql驱动properties springboot怎么配置mybatis_intellij-idea_05

  1. 创建数据库,名为user 
  2. 在resources文件夹下建立config文件夹,存放mybatis的配置文件 mybatis-config.xml,(地址报红可暂且不管。后面引入MyBatis依赖即可解决)代码如下:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- 批量别名定义,扫描整个包下的类,别名为类名(首字母大写或小写都可以) -->
    <!-- 用于指定要配置别名的包,指定后,该包下的实体类都会注册别名,并且类名就是别名,不再区分大小写 -->
    <typeAliases>
        <package name="com.demo.test.entity"></package>
    </typeAliases>
</configuration>
  1. 可将application.properties文件改成application.yml文件,代码如下:
# 配置端口
server:
  port: 8081

# 连接数据库
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/test?useSSL=false&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    password: 123456
    username: root
    driver-class-name: com.mysql.jdbc.Driver

# mybatis环境配置
mybatis:
  config-location: classpath:config/mybatis-config.xml
  mapper-locations: classpath:mapper/*.xml
  1. 前面创建项目时,如果没有选择添加Web,Mysql Driver,Mybatis三个依赖,可在pom.xml中选择加入以下三个依赖(代码在第3点),刷新依赖即可。

 11.运行启动类TestApplication,如图点击左上角(有些IDEA版本在右上角)的箭头;或者进入启动类TestApplication里,点击绿色的三角形里的绿色三角形run。成功启动项目控制台会有如下信息(JVM running for…).

springboot配置mysql驱动properties springboot怎么配置mybatis_sed_06

项目架构搭建

1.在test包下,创建4个包(与启动类TestApplication同级),分别是controller,dao,entity,还有service。
选中test文件夹,鼠标右键,选择new列表下的Packeage,

鼠标右键service包,在此包下再创建一个impl包,存放service实现类。

springboot配置mysql驱动properties springboot怎么配置mybatis_intellij-idea_07

2.在resources目录下,再新建一个mapper文件夹,并创建TestMapper.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">
<!--namespace绑定Dao接口,你可以不用写接口实现类,mybatis会通过该绑定自动帮你找到对应要执行的SQL语句-->
<mapper namespace="com.demo.test.dao.UserDao">

    <!--    获取指定id 的用户-->
    <select id="findById" parameterType="String" resultType="User">
        select * from user where id = #{id}
    </select>

    <!--    原始登录-->
    <select id="login" parameterType="String" resultType="String">
        select password from user where username = #{username}
    </select>

</mapper>

 3.在entity包下创建实体类User,代码如下:

package com.demo.test.entity;

public class User {
    private Integer id;
    private String username;
    private String password;
    private Integer age;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                '}';
    }
}

4.在dao包下创建UserDao接口,代码如下:

package com.demo.test.dao;

import com.demo.test.entity.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Component;


//Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注
@Component
public interface UserDao {

    //获取指定id 的用户
    User findById(@Param("id")String id);

    //原始登录
    String login(@Param("username")String username);

}

5.在service包下创建UserService接口,代码如下:

package com.demo.test.service;


import com.demo.test.entity.User;

public interface UserService {

    User findById(String id);

    String login(String username);
}

6.在service包下的impl包下,创建UserServiceImpl实现类,代码如下:

package com.demo.test.service.impl;

import com.demo.test.dao.UserDao;
import com.demo.test.entity.User;
import com.demo.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

//Service注解,将自动注册到Spring容器,不需要再在applicationContext.xml文件定义bean了.一般用于service层的实现类
// 类似的还包括@Component、@Repository、@Controller。
@Service
public class UserServiceImpl implements UserService {

    //@Autowired是一种注解,可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作
    @Autowired
    private UserDao userDao;

    //获取指定id 的用户
    //Override下面的方法名是否是你父类中所有的,如果没有则报错。
    @Override
    public User findById(String id) {
        return userDao.findById(id);
    }

    //原始登录
    @Override
    public String login(String username) {
        return userDao.login(username);
    }
}

7.在controller包下,创建TestController,代码如下:

package com.demo.test.controller;

import com.demo.test.entity.User;
import com.demo.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import java.util.Map;


@RestController     //@Controller+@ResponseBody,就不能返回jsp,html页面
@RequestMapping("/user")        //将HTTP请求映射给controller,即请求路径
public class UserController {

    @Autowired
    private UserService userService;

    //获取指定id的用户信息
    @GetMapping("/test")     //等价于@RequestMapping的GET请求方式,@RequestParam将请求参数绑定到你控制器的方法参数上
    public User findUser(@RequestParam(value = "id") String id){
        return userService.findById(id);
    }


    //原始登录接口
    @RequestMapping(value = "login")
    //使用ModelAndView类用来存储处理完后的结果数据,以及显示该数据的视图。
    //Map是一个接口,即Interface Map<K,V>,其中K-key类型和V-value的类型
    public ModelAndView login(@RequestParam Map<String,Object> map){

        String username = (String) map.get("name");
        String password = (String) map.get("pass");
        System.out.println("前端发来用户信息,用户名:"+username+"——密码:"+password);

        String result = userService.login(username);
        if (password.equals(result)){
            map.put("code",200);
            map.put("massage","成功接收数据");
        }
        else {
            map.put("code",201);
            map.put("massage","密码错误");
        }

        return new ModelAndView(new MappingJackson2JsonView(),map);

    }


}

8.最后,在启动类TestApplication中,添加上注解扫描@MapperScan(“com.demo.test.dao”),然后启动。

springboot配置mysql驱动properties springboot怎么配置mybatis_mybatis_08

9.项目成功启动后,打开浏览器,输入地址:

http://localhost:8080/user/login?name=zhangsan&pass=123456(name和pass为数据库的数据)

springboot配置mysql驱动properties springboot怎么配置mybatis_xml_09

补充:

接口返回json数据

  1. 上文提到的使用User类型、ModelAndView类型返回的json数据都不熟很规范。下面将新建一个实体类CommonResult,作为返回的实体类。可直接放于Entity包下,代码如下:
package com.demo.test.entity;


public class CommonResult<T> {
    private Integer code;
    private String massage;
    private T data;

    public CommonResult(Integer code,String massage){

        this(code,massage,null);

    }

    public CommonResult(Integer code, String massage, T data) {
        this.code = code;
        this.massage = massage;
        this.data = data;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMassage() {
        return massage;
    }

    public void setMassage(String massage) {
        this.massage = massage;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "CommonResult{" +
                "code=" + code +
                ", massage='" + massage + '\'' +
                ", data=" + data +
                '}';
    }
}

 2,建完CommonResult实体类后,修改原本的controller层,应用此实体类作为返回类型,只修改了findUser方法的代码,代码如下:

package com.demo.test.controller;

import com.demo.test.entity.CommonResult;
import com.demo.test.entity.User;
import com.demo.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import java.util.Map;


@RestController     //@Controller+@ResponseBody,就不能返回jsp,html页面
@RequestMapping("/user")        //将HTTP请求映射给controller,即请求路径
public class UserController {

    @Autowired
    private UserService userService;

    //获取指定id的用户信息
    @GetMapping("/test")     //等价于@RequestMapping的GET请求方式,@RequestParam将请求参数绑定到你控制器的方法参数上
    public CommonResult findUser(@RequestParam(value = "id") String id){
        CommonResult commonResult = new CommonResult(200,"查询成功", userService.findById(id));
        return commonResult;
    }

    //原始登录接口
    @RequestMapping(value = "login")
    //使用ModelAndView类用来存储处理完后的结果数据,以及显示该数据的视图。
    //Map是一个接口,即Interface Map<K,V>,其中K-key类型和V-value的类型
    public ModelAndView login(@RequestParam Map<String,Object> map){

        String username = (String) map.get("name");
        String password = (String) map.get("pass");
        System.out.println("前端发来用户信息,用户名:"+username+"——密码:"+password);

        String result = userService.login(username);
        if (password.equals(result)){
            map.put("code",200);
            map.put("massage","成功接收数据");
        }
        else {
            map.put("code",201);
            map.put("massage","密码错误");
        }

        return new ModelAndView(new MappingJackson2JsonView(),map);

    }


}

springboot配置mysql驱动properties springboot怎么配置mybatis_xml_10

将mybatis替换成mybtis-plus。

1.MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

2.将pom.xml文件里的mybatis依赖,更换成mybatis-plus

<dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>3.4.1</version>
</dependency>

完整pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.demo</groupId>
    <artifactId>test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>test</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.25</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
<!--        <dependency>-->
<!--            <groupId>org.mybatis.spring.boot</groupId>-->
<!--            <artifactId>mybatis-spring-boot-starter</artifactId>-->
<!--            <version>2.1.3</version>-->
<!--        </dependency>-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>



        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2.将application.yml文件里的mybatis头改成mybatis-plus,如图,只改图中红线一处,其余无需更改

springboot配置mysql驱动properties springboot怎么配置mybatis_intellij-idea_11

3.新建一个config文件夹,存放MybatisPlusConfig文件(分页插件配置,不做分页可不加)

package com.demo.test.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MybatisPlusConfig {
    /**
     * 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.H2));
        return interceptor;
    }

    @Bean
    public ConfigurationCustomizer configurationCustomizer() {
        return configuration -> configuration.setUseDeprecatedExecutor(false);
    }
}

springboot配置mysql驱动properties springboot怎么配置mybatis_xml_12

4.在UserDao接口类中,继承BaseMapper,普通增删查改都无需再写接口 

 

springboot配置mysql驱动properties springboot怎么配置mybatis_mybatis_13

5.测试

打开最下方的Test文件,找到TestApplicationTests,进行测试

springboot配置mysql驱动properties springboot怎么配置mybatis_intellij-idea_14

 

代码入下:

package com.demo.test;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.test.dao.UserDao;
import com.demo.test.entity.User;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;
import java.util.Map;

@SpringBootTest
class TestApplicationTests {

    @Autowired
    private UserDao userDao;

    @Test
    void contextLoads() {

        // 根据 ID 查询
        User user = userDao.findById("1");
        System.out.println("对应id的用户为:"+user);

        //分页、条件、模糊查询
        Page<User> page = new Page<>(1, 5);
        page.addOrder(OrderItem.asc("age"));
        Page<User> userIPage = userDao.selectPage(page, Wrappers.<User>lambdaQuery().eq(User::getAge, 11).like(User::getUsername, "A"));
        Assertions.assertThat(page).isSameAs(userIPage);
        System.out.println("总条数 -------------> {}"+userIPage.getTotal());
        System.out.println("当前页数 --- -------------> {}"+userIPage.getCurrent());
        System.out.println("当前每页显示数 -----------> {}"+userIPage.getSize());
        List<User> records = userIPage.getRecords();
        Assertions.assertThat(records).isNotEmpty();
        System.out.println(records);
    }

}

 

springboot配置mysql驱动properties springboot怎么配置mybatis_mybatis_15

Mybatis-Plus分页条件查询 

1.Dao层继承BaseMapper后,不进行复杂的操作,都可以不管了
2.在service层写上接口方法

// 分页查询
    IPage<User> selectPage(IPage<User> page, @Param("ew") Wrapper<User> queryWrapper);

3.在impl中实现方法

//分页条件查询
    @Override
    public IPage<User> selectPage(IPage<User> page, Wrapper<User> queryWrapper) {
        return userDao.selectPage(page,queryWrapper);
    }

4.在controller中写入

//分页条件查询,按年龄查询,按用户名模糊查询都是可选参数
    @PostMapping("/selectPage")     //等价于@RequestMapping的GET请求方式,@RequestParam将请求参数绑定到你控制器的方法参数上
    public CommonResult selectPage(@RequestParam(value = "pageSize") Integer pageSize,@RequestParam(value = "current") Integer current,
                                   @RequestParam(value = "age",required=false) Integer age,@RequestParam(value = "username",required=false) String username){
        Page<User> page = new Page<>(current, pageSize);

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (age != null){
            //不为空则加入条件
            queryWrapper.eq("age",age);                 //按年龄查询
        }
        if (!StringUtils.isEmpty(username)){
            //不为空则加入条件
            queryWrapper.like("username",username);     //按用户名模糊查询
        }
        CommonResult commonResult = new CommonResult(200,"查询成功", userService.selectPage(page,queryWrapper));
        return commonResult;
    }

在Apifox中http://localhost:8080/user/selectPage(Apifox可以下载电脑版,或者直接web版,web版要在浏览器中添加扩展程序插件)

springboot配置mysql驱动properties springboot怎么配置mybatis_sed_16