• MyBatisPlus快速入门


    MyBatisPlus快速入门

    官方网站
    https://mp.baomidou.com/guide
    慕课网视频
    https://www.imooc.com/learn/1130 入门
    https://www.imooc.com/learn/1171 进阶
    

    1.引入依赖和springboot配置

    2.实体类和数据库表

    3.Mapper接口

    4.Mapper映射文件(可选)

    5.测试类

    引入依赖和springboot配置

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    
    <properties>
        <java.version>1.8</java.version>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
    
    spring:
      datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        url: jdbc:mysql://localhost:3306/db1?userSSL=false&serverTimezone=GMT%2B8&characterEncoding=utf-8
        username: root
        password: root
    

    实体类和数据库表

    #创建用户表
    #mysql> show collation;
    #mysql> show collate;
    #mysql> show charset;
    
    drop database if exists mp_01; 
    create database mp_01 character set utf8mb4 collate utf8mb4_general_ci;
    use mp_01;
    
    drop table if exists user;
    CREATE TABLE user (
        id BIGINT(20) PRIMARY KEY NOT NULL COMMENT '主键',
        name VARCHAR(30) DEFAULT NULL COMMENT '姓名',
        age INT(11) DEFAULT NULL COMMENT '年龄',
        email VARCHAR(50) DEFAULT NULL COMMENT '邮箱',
        manager_id BIGINT(20) DEFAULT NULL COMMENT '直属上级id',
        create_time DATETIME DEFAULT NULL COMMENT '创建时间',
        CONSTRAINT manager_fk FOREIGN KEY (manager_id)
            REFERENCES user (id)
    )  ENGINE=INNODB CHARSET=UTF8;
    
    #初始化数据:
    INSERT INTO user (id, name, age, email, manager_id
    	, create_time)
    VALUES (1087982257332887553, '大boss', 40, 'boss@baomidou.com', NULL
    		, '2019-01-11 14:20:20'),
    	(1088248166370832385, '王天风', 25, 'wtf@baomidou.com', 1087982257332887553
    		, '2019-02-05 11:12:22'),
    	(1088250446457389058, '李艺伟', 28, 'lyw@baomidou.com', 1088248166370832385
    		, '2019-02-14 08:31:16'),
    	(1094590409767661570, '张雨琪', 31, 'zjq@baomidou.com', 1088248166370832385
    		, '2019-01-14 09:15:15'),
    	(1094592041087729666, '刘红雨', 32, 'lhm@baomidou.com', 1088248166370832385
    		, '2019-01-14 09:48:16');
    
    package com.mp.mybatis01.entity;
    
    import com.baomidou.mybatisplus.annotation.TableField;
    import com.baomidou.mybatisplus.annotation.TableId;
    import com.baomidou.mybatisplus.annotation.TableName;
    import lombok.Data;
    
    import java.io.Serializable;
    import java.time.LocalDateTime;
    
    @Data
    @TableName("mp_user")
    public class User implements Serializable {
        @TableId
        private Long userId;
        @TableField("name")
        private String realName;
        private Integer age;
        private String email;
        private Long managerId;
        private LocalDateTime createTime;
    
        //不对应表中字段 1.静态字段 2.瞬时字段 3.@TableField(exist = false)
    //    private transient String remark;
    
    //    private static String remark;
    //    public static String getRemark(){return remark;}
    //    public static void setRemark(String remark){
    //        User.remark = remark;
    //    }
    
        @TableField(exist = false)
        private String remark;
    
    }
    

    Mapper接口

    package com.mp.mybatis01.dao;
    
    import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    import org.apache.ibatis.annotations.Mapper;
    import java.util.List;
    //@Mapper标识MyBatis的Mapper接口,@MapperScan用于扫描MyBatis的Mapper接口
    @Mapper
    public interface UserMapper extends BaseMapper<User> {
    }
    

    测试类

    package com.mp.mybatis01.dao;
    
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.mp.mybatis01.entity.User;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class UserMapperTest {
        @Autowired
        private UserMapper userMapper;
    
        @Test
        public void selectList(){
            List<User> users = userMapper.selectList(null);
            users.forEach(System.out::println);
        }
    
        //如果插入成功则返回自动生成的主键
        @Test
        public void insert(){
            User user = new User();
    //        user.setId(1180761990619959297L);
    //        user.setName("刘备");
            user.setRemark("这是备注");
            user.setRealName("刘备");
            user.setAge(25);
            int rows = userMapper.insert(user);
            System.out.println(rows);
            System.out.println(user);
        }
    
        @Test
        public void selectById(){
            User user = userMapper.selectById(1087982257332887553L);
            System.out.println(user);
        }
    
        @Test
        public void selectBatchIds(){
    //        List<User> users = userMapper.selectBatchIds(null);
    
    //        List<Long> idList = new ArrayList<>();
    //        List<User> users = userMapper.selectBatchIds(idList);
    
            List<Long> idList = new ArrayList<>();
            idList.add(1087982257332887553L);
            idList.add(1088248166370832385L);
            idList.add(1088250446457389058L);
            List<User> users = userMapper.selectBatchIds(idList);
            users.forEach(System.out::println);
        }
    
        @Test
        public void selectByMap(){
            HashMap<String, Object> condition = new HashMap<>();
            condition.put("name", "刘备");
            condition.put("age", 25);
            List<User> users = userMapper.selectByMap(condition);
            users.forEach(System.out::println);
        }
    
        @Test
        public void selectList2(){
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("age", 25).likeLeft("name", "备");
            List<User> users = userMapper.selectList(queryWrapper);
            users.forEach(System.out::println);
        }
    
        @Test
        public void selectList3(){
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper =  queryWrapper.inSql("manager_id", "select user_id from mp_user where name like '%大%' ");
            List<User> users = userMapper.selectList(queryWrapper);
            users.forEach(System.out::println);
        }
    
        @Test
        public void selectList4(){
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.nested(wq->wq.lt("age", 40).or().isNotNull("email")).likeRight("name", "王");
            List<User> users = userMapper.selectList(queryWrapper);
            users.forEach(System.out::println);
        }
    
        @Test
        public void selectList5(){
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("user_id", "realName").like("name", "刘备");
            List<User> users = userMapper.selectList(queryWrapper);
            users.forEach(System.out::println);
        }
    
    }
    

    Mapper映射文件

    mybatis-plus:
      configuration:
        log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 打印sql
      mapper-locations: classpath:mapper/*.xml #映射文件位置
      type-aliases-package: com.mp.mybatis01.entity #实体类别名
    
    <?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.mp.mybatis01.dao.UserMapper">
        <select id="selectByName" resultType="User">
          select * from mp_user where name = #{name}
        </select>
    </mapper>
    
    package com.mp.mybatis01.dao;
    
    import com.baomidou.mybatisplus.core.mapper.BaseMapper;
    import com.mp.mybatis01.entity.User;
    import org.apache.ibatis.annotations.Select;
    
    import java.util.List;
    
    //@Mapper标识MyBatis的Mapper接口,@MapperScan用于扫描MyBatis的Mapper接口
    @Mapper
    public interface UserMapper extends BaseMapper<User> {
    
        List<User> selectByName(String name);
    
        @Select("select * from mp_user where age > #{age}")
        List<User> selectByAge(Integer age);
    }
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class UserMapperTest {
        @Autowired
        private UserMapper userMapper;
        @Test
        public void selectByName(){
            List<User> users = userMapper.selectByName("王天风");
            users.forEach(System.out::println);
        }
    
        @Test
        public void selectByAge(){
            List<User> users = userMapper.selectByAge(20);
            users.forEach(System.out::println);
        }
    }
    
  • 相关阅读:
    U盘安装Ubuntu 14.04 LTS
    VS2013配置OPENCV2.4.9(OPENCV3.X)
    make、makefile、cmake、qmake对比
    Google C++ Style
    Ubuntu16.04搜狗输入法无法输入中文
    Ubuntu16.04安装使用wineqq
    Ubuntu卸载软件
    [机器学习入门篇]-梯度下降法
    [机器学习入门篇]-正则化
    2014年度最受好评的十佳工具
  • 原文地址:https://www.cnblogs.com/mozq/p/11628556.html
Copyright © 2020-2023  润新知