Mybatis-Plus01 快速上手

Posted Silent1376

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis-Plus01 快速上手相关的知识,希望对你有一定的参考价值。

【官网快速上手地址】

https://mp.baomidou.com/guide/quick-start.html#%E5%88%9D%E5%A7%8B%E5%8C%96%E5%B7%A5%E7%A8%8B

 

创建一个空的数据库,并插入user表和数据:

DROP TABLE IF EXISTS user;

CREATE TABLE user
(
    id BIGINT(20) NOT NULL COMMENT \'主键ID\',
    name VARCHAR(30) NULL DEFAULT NULL COMMENT \'姓名\',
    age INT(11) NULL DEFAULT NULL COMMENT \'年龄\',
    email VARCHAR(50) NULL DEFAULT NULL COMMENT \'邮箱\',
    PRIMARY KEY (id)
);


DELETE FROM user;

INSERT INTO user (id, name, age, email) VALUES
(1, \'Jone\', 18, \'test1@baomidou.com\'),
(2, \'Jack\', 20, \'test2@baomidou.com\'),
(3, \'Tom\', 28, \'test3@baomidou.com\'),
(4, \'Sandy\', 21, \'test4@baomidou.com\'),
(5, \'Billie\', 24, \'test5@baomidou.com\');

 

然后使用IDEA创建SpringBoot项目,不需要点击任何工具选项:

进入项目导入pom坐标:

        <!-- JDBC -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <!-- lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <!-- mybatis-plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.2</version>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

 

【application.properties】

配置连接参数:

spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
spring.datasource.url = jdbc:mysql://49.234.116.100:3306/mybatis_plus?serverTimezone=GMT
spring.datasource.username = root 
spring.datasource.password = 123456 

编写实体类:

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Integer id;
    private String name;
    private Integer age;
    private String email;
}

 

编写User的Mapper接口,使用Mybatis-Plus,将接口继承BaseMapper

public interface UserMapper extends BaseMapper<User> {
    
}

【回顾我的阶段一项目,当时就这么写过一个基本的BaseDao接口...】

CRUD的代码已经由mybatis-plus帮助我们完成了

 

BaseMapper接口的源码:

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.baomidou.mybatisplus.core.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;

public interface BaseMapper<T> extends Mapper<T> {
    int insert(T entity);

    int deleteById(Serializable id);

    int deleteByMap(@Param("cm") Map<String, Object> columnMap);

    int delete(@Param("ew") Wrapper<T> wrapper);

    int deleteBatchIds(@Param("coll") Collection<? extends Serializable> idList);

    int updateById(@Param("et") T entity);

    int update(@Param("et") T entity, @Param("ew") Wrapper<T> updateWrapper);

    T selectById(Serializable id);

    List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);

    List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);

    T selectOne(@Param("ew") Wrapper<T> queryWrapper);

    Integer selectCount(@Param("ew") Wrapper<T> queryWrapper);

    List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);

    List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);

    List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);

    <E extends IPage<T>> E selectPage(E page, @Param("ew") Wrapper<T> queryWrapper);

    <E extends IPage<Map<String, Object>>> E selectMapsPage(E page, @Param("ew") Wrapper<T> queryWrapper);
}

 

别忘了加持久层注解

在Main方法的类上面添加Mapper扫描注解

 

测试类:

@SpringBootTest
class MybatisPlusApplicationTests {

    @Autowired // 自动装配
    private UserMapper userMapper;

    @Test
    void contextLoads() {
        // wrapper 是一个封装查询条件的对象,如果不需要条件不就是null
        List<User> userList = userMapper.selectList(null);
        // lambda表达式
        userList.forEach(System.out::print);
    }

}

 

执行结果:

11:02:18.166 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
11:02:18.185 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
11:02:18.231 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [cn.echo42.MybatisPlusApplicationTests] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
11:02:18.257 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [cn.echo42.MybatisPlusApplicationTests], using SpringBootContextLoader
11:02:18.263 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [cn.echo42.MybatisPlusApplicationTests]: class path resource [cn/echo42/MybatisPlusApplicationTests-context.xml] does not exist
11:02:18.263 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [cn.echo42.MybatisPlusApplicationTests]: class path resource [cn/echo42/MybatisPlusApplicationTestsContext.groovy] does not exist
11:02:18.264 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [cn.echo42.MybatisPlusApplicationTests]: no resource found for suffixes {-context.xml, Context.groovy}.
11:02:18.265 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [cn.echo42.MybatisPlusApplicationTests]: MybatisPlusApplicationTests does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
11:02:18.329 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an \'annotation declaring class\' for annotation type [org.springframework.test.context.ActiveProfiles] and class [cn.echo42.MybatisPlusApplicationTests]
11:02:18.456 [main] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [C:\\Users\\User-Dai\\IdeaProjects\\Mybatis-Plus\\target\\classes\\cn\\echo42\\MybatisPlusApplication.class]
11:02:18.457 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration cn.echo42.MybatisPlusApplication for test class cn.echo42.MybatisPlusApplicationTests
11:02:18.630 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [cn.echo42.MybatisPlusApplicationTests]: using defaults.
11:02:18.631 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
11:02:18.660 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@437da279, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@23c30a20, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@1e1a0406, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@3cebbb30, org.springframework.test.context.support.DirtiesContextTestExecutionListener@12aba8be, org.springframework.test.context.transaction.TransactionalTestExecutionListener@290222c1, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@67f639d3, org.springframework.test.context.event.EventPublishingTestExecutionListener@6253c26, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@49049a04, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@71a8adcf, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@27462a88, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@82de64a, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@659499f1, org.springframework.boot.test.autoconfigure.webservices.client.MockWebServiceServerTestExecutionListener@51e69659]
11:02:18.667 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@d9345cd testClass = MybatisPlusApplicationTests, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@2d710f1a testClass = MybatisPlusApplicationTests, locations = \'{}\', classes = \'{class cn.echo42.MybatisPlusApplication}\', contextInitializerClasses = \'[]\', activeProfiles = \'{}\', propertySourceLocations = \'{}\', propertySourceProperties = \'{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}\', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@1f0f1111, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@6e0dec4a, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@47d90b9e, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@3d680b5a, org.springframework.boot.test.context.SpringBootTestArgs@1], resourceBasePath = \'src/main/webapp\', contextLoader = \'org.springframework.boot.test.context.SpringBootContextLoader\', parent = [null]], attributes = map[\'org.springframework.test.context.web.ServletTestExecutionListener.activateListener\' -> true]], class annotated with @DirtiesContext [false] with mode [null].
11:02:18.725 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}

  .   ____          _            __ _ _
 /\\\\ / ___\'_ __ _ _(_)_ __  __ _ \\ \\ \\ \\
( ( )\\___ | \'_ | \'_| | \'_ \\/ _` | \\ \\ \\ \\
 \\\\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  \'  |____| .__|_| |_|_| |_\\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.3.1.RELEASE)

2020-07-20 11:02:19.217  INFO 17456 --- [           main] cn.echo42.MybatisPlusApplicationTests    : Starting MybatisPlusApplicationTests on DESKTOP-SDT4NG3 with PID 17456 (started by User-Dai in C:\\Users\\User-Dai\\IdeaProjects\\Mybatis-Plus)
2020-07-20 11:02:19.220  INFO 17456 --- [           main] cn.echo42.MybatisPlusApplicationTests    : No active profile set, falling back to default profiles: default
2020-07-20 11:02:21.126  INFO 17456 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService \'applicationTaskExecutor\'
 _ _   |_  _ _|_. ___ _ |    _ 
| | |\\/|_)(_| | |_\\  |_)||_|_\\ 
     /               |         
                        3.3.2 
2020-07-20 11:02:22.667  INFO 17456 --- [           main] cn.echo42.MybatisPlusApplicationTests    : Started MybatisPlusApplicationTests in 3.924 seconds (JVM running for 5.415)

2020-07-20 11:02:23.043  INFO 17456 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-07-20 11:02:26.071  INFO 17456 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
User(id=1, name=Jone, age=18, email=test1@baomidou.com)User(id=2, name=Jack, age=20, email=test2@baomidou.com)User(id=3, name=Tom, age=28, email=test3@baomidou.com)User(id=4, name=Sandy, age=21, email=test4@baomidou.com)User(id=5, name=Billie, age=24, email=test5@baomidou.com)
2020-07-20 11:02:26.215  INFO 17456 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2020-07-20 11:02:26.472  INFO 17456 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.
2020-07-20 11:02:26.473  INFO 17456 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService \'applicationTaskExecutor\'

Process finished with exit code 0

 

可以看到这里控制台的输出是没有打印SQL执行的,

所以我们需要配置日志输出

【application.properties】

# 日志配置
mybatis-plus.configuration.log-impl = org.apache.ibatis.logging.stdout.StdOutImpl

二次执行:

Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1687eb01] was not registered for synchronization because synchronization is not active
2020-07-20 11:07:10.780  INFO 25940 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-07-20 11:07:12.318  INFO 25940 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@1674550752 wrapping com.mysql.cj.jdbc.ConnectionImpl@594d9f07] will not be managed by Spring
==>  Preparing: SELECT id,name,age,email FROM user 
==> Parameters: 
<==    Columns: id, name, age, email
<==        Row: 1, Jone, 18, test1@baomidou.com
<==        Row: 2, Jack, 20, test2@baomidou.com
<==        Row: 3, Tom, 28, test3@baomidou.com
<==        Row: 4, Sandy, 21, test4@baomidou.com
<==        Row: 5, Billie, 24, test5@baomidou.com
<==      Total: 5
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1687eb01]
User(id=1, name=Jone, age=18, email=test1@baomidou.com)User(id=2, name=Jack, age=20, email=test2@baomidou.com)User(id=3, name=Tom, age=28, email=test3@baomidou.com)User(id=4, name=Sandy, age=21, email=test4@baomidou.com)User(id=5, name=Billie, age=24, email=test5@baomidou.com)
2020-07-20 11:07:12.506  INFO 25940 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2020-07-20 11:07:12.891  INFO 25940 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.
2020-07-20 11:07:12.892  INFO 25940 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService \'applicationTaskExecutor\'

Process finished with exit code 0

 

【CRUD基操】

执行插入测试:

    @Test
    void insertUser() {
        int insert = userMapper.insert(
                new User(
                        null,
                        "啊啊啊",
                        22,
                        "1791255334@qq.com"
                )
        );
    }

插入失败:

org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: Could not set property \'id\' of \'class cn.echo42.pojo.User\' with value \'1285049463613612034\' Cause: java.lang.IllegalArgumentException: argument type mismatch

最终原因是因为类型不匹配:

java.lang.IllegalArgumentException: argument type mismatch

在我们User对象id属性设置null进行插入时,mybatis会自动生成一个UID插入

但是显然超出Integer的范围,所以改用Long试试

private Long id;

测试结果果然成功:

Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@237f7970] was not registered for synchronization because synchronization is not active
2020-07-20 11:16:52.830  INFO 19932 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-07-20 11:16:54.222  INFO 19932 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@441867003 wrapping com.mysql.cj.jdbc.ConnectionImpl@2fd64b11] will not be managed by Spring
==>  Preparing: INSERT INTO user ( id, name, age, email ) VALUES ( ?, ?, ?, ? ) 
==> Parameters: 1285051019587166210(Long), 啊啊啊(String), 22(Integer), 1791255334@qq.com(String)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@237f7970]

2020-07-20 11:16:54.371  INFO 19932 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2020-07-20 11:16:54.707  INFO 19932 --- [extShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.
2020-07-20 11:16:54.709  INFO 19932 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService \'applicationTaskExecutor\'

Process finished with exit code 0

 

数据库查看:

 

【主键生成策略】 

自增
uuid
redis
zookeeper
snowflake 雪花算法 

似乎Mybatis-Plus默认采用的生成策略是雪花算法

如果要更改策略的话使用@TableId注解更改

可以打开看看这个type的枚举类

package com.baomidou.mybatisplus.annotation;

public enum IdType {
    AUTO(0),
    NONE(1),
    INPUT(2),
    ASSIGN_ID(3),
    ASSIGN_UUID(4),
    /** @deprecated */
    @Deprecated
    ID_WORKER(3),
    /** @deprecated */
    @Deprecated
    ID_WORKER_STR(3),
    /** @deprecated */
    @Deprecated
    UUID(4);

    private final int key;

    private IdType(int key) {
        this.key = key;
    }

    public int getKey() {
        return this.key;
    }
}

 

以上是关于Mybatis-Plus01 快速上手的主要内容,如果未能解决你的问题,请参考以下文章

优雅高效的MyBatis-Plus工具快速入门使用

mybatis plus 快速上手

mybatis plus 快速上手

mybatis-plus学习笔记

Mybatis-Plus:快速开始(SpringBoot + Mybatis + Mybatis)

Mybatis-Plus:了解Mybatis-Plus快速开始(Mybatis + Mybatis-Plus,Mybatis-Plus自动做了属性映射)