Mybatis-Plus-入门简介(2)

Mybatis-Plus-入门简介

1.简介

Mybatis-Plus官网:https://baomidou.com/

Mybatis-Plus仓库地址:https://mvnrepository.com/artifact/com.baomidou/mybatis-plus-boot-starter

仓库地址:仓库地址:https://gitee.com/long-xiaozhen/learning-mybatis-plus.git

1.1快速开始

创建基本的测试的表

直接照着执行,不需要创建库

-- --------------------------------------------------------
-- 主机:                           127.0.0.1
-- 服务器版本:                        8.0.28 - MySQL Community Server - GPL
-- 服务器操作系统:                      Win64
-- HeidiSQL 版本:                  12.2.0.6576
-- --------------------------------------------------------
 
-- 导出 mp 的数据库结构
CREATE DATABASE IF NOT EXISTS `mp` /*!40100 DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci */ /*!80016 DEFAULT ENCRYPTION='N' */;
USE `mp`;
 
-- 导出  表 mp.address 结构
CREATE TABLE IF NOT EXISTS `address` (
  `id` bigint NOT NULL AUTO_INCREMENT,
  `user_id` bigint DEFAULT NULL COMMENT '用户ID',
  `province` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '省',
  `city` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '市',
  `town` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '县/区',
  `mobile` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '手机',
  `street` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '详细地址',
  `contact` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '联系人',
  `is_default` bit(1) DEFAULT b'0' COMMENT '是否是默认 1默认 0否',
  `notes` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '备注',
  PRIMARY KEY (`id`) USING BTREE,
  KEY `user_id` (`user_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=67 DEFAULT CHARSET=utf8mb3 ROW_FORMAT=COMPACT;
 
-- 正在导出表  mp.address 的数据:~7 rows (大约)
DELETE FROM `address`;
INSERT INTO `address` (`id`, `user_id`, `province`, `city`, `town`, `mobile`, `street`, `contact`, `is_default`, `notes`) VALUES
    (59, 2, '北京', '北京', '朝阳区', '13900112222', '金燕龙办公楼', 'Rose', b'1', NULL),
    (60, 1, '北京', '北京', '朝阳区', '13700221122', '修正大厦', 'Jack', b'0', NULL),
    (61, 1, '上海', '上海', '浦东新区', '13301212233', '航头镇航头路', 'Jack', b'1', NULL),
    (63, 2, '广东', '佛山', '永春', '13301212233', '永春武馆', 'Rose', b'0', NULL),
    (64, 3, '浙江', '杭州', '拱墅区', '13567809102', '浙江大学', 'Hope', b'1', NULL),
    (65, 3, '浙江', '杭州', '拱墅区', '13967589201', '左岸花园', 'Hope', b'0', NULL),
    (66, 4, '湖北', '武汉', '汉口', '13967519202', '天天花园', 'Thomas', b'1', NULL);
 
-- 导出  表 mp.user 结构
CREATE TABLE IF NOT EXISTS `user` (
  `id` bigint NOT NULL AUTO_INCREMENT COMMENT '用户id',
  `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名',
  `password` varchar(128) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码',
  `phone` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '注册手机号',
  `info` json NOT NULL COMMENT '详细信息',
  `status` int DEFAULT '1' COMMENT '使用状态(1正常 2冻结)',
  `balance` int DEFAULT NULL COMMENT '账户余额',
  `create_time` datetime NOT NULL COMMENT '创建时间',
  `update_time` datetime NOT NULL COMMENT '更新时间',
  PRIMARY KEY (`id`) USING BTREE,
  UNIQUE KEY `username` (`username`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=1674613593516095922 DEFAULT CHARSET=utf8mb3 ROW_FORMAT=COMPACT COMMENT='用户表';
 
-- 正在导出表  mp.user 的数据:~4 rows (大约)
DELETE FROM `user`;
INSERT INTO `user` (`id`, `username`, `password`, `phone`, `info`, `status`, `balance`, `create_time`, `update_time`) VALUES
    (1, 'Jack', '123', '13900112224', '{"age": 20, "intro": "佛系青年", "gender": "male"}', 1, 1600, '2023-05-19 20:50:21', '2023-06-19 20:50:21'),
    (2, 'Rose', '123', '13900112223', '{"age": 19, "intro": "青涩少女", "gender": "female"}', 1, 300, '2023-05-19 21:00:23', '2023-06-19 21:00:23'),
    (3, 'Hope', '123', '13900112222', '{"age": 25, "intro": "上进青年", "gender": "male"}', 1, 100000, '2023-06-19 22:37:44', '2023-06-19 22:37:44'),
    (4, 'Thomas', '123', '17701265258', '{"age": 29, "intro": "伏地魔", "gender": "male"}', 1, 800, '2023-06-19 23:44:45', '2023-06-19 23:44:45');
 
/*!40103 SET TIME_ZONE=IFNULL(@OLD_TIME_ZONE, 'system') */;
/*!40101 SET SQL_MODE=IFNULL(@OLD_SQL_MODE, '') */;
/*!40014 SET FOREIGN_KEY_CHECKS=IFNULL(@OLD_FOREIGN_KEY_CHECKS, 1) */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40111 SET SQL_NOTES=IFNULL(@OLD_SQL_NOTES, 1) */;

在这里插入图片描述

在这里插入图片描述

1.2创建基本的my的结构

父依赖

    <dependencies>
<!--        test-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
<!--        hutool工具包-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.8.11</version>
        </dependency>
<!--        JSON 数据的序列化和反序列化-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-json</artifactId>
        </dependency>
<!--        lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <!--          dependencies起到的是版本依赖的管理 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

注意想用Db这个静态类的话需要打入下面版本的依赖

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

原先的3.5.2的是没有的。

依赖

  <dependencies>
        <!--        spring-web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- MySQL 驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
        <!--        mybatis-plus-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.2</version>
        </dependency>

    </dependencies>

    <build>
        <!--项目打包时会讲java目录中的*.xml文件也进行打包-->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

创建配置文件

server:
  port: 8081
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mp?useSSL=false&serverTimezone=Asia/Shanghai
    username: root
    password: root
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
    map-underscore-to-camel-case: true  #开启驼峰命名匹配
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.lxz.demo.domain

代码生成基本的结构。

在这里插入图片描述

1.3创建完项目之后完成基本的测试的工作

在这里插入图片描述
创建基本的测试代码的结构

@SpringBootTest
public class TestApplication {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AddressMapper addressMapper;

//编写相关的测试的代码
}

注意下面的json需要转换成string类型的字符串才能进行插入的

测试插入的代码


 @Test
    void test1(){
        //要么就是insert就是save,创建一个User对象就写入进行就可以的
        User user=new User();
        user.setUsername("张三");
        user.setPassword("13900112224");
        JSONObject jsonObject=new JSONObject();
        //hutool中的
        jsonObject.set("age",29);
        jsonObject.set("intro","伏地魔");
        jsonObject.set("gender","male");
        user.setInfo(jsonObject.toString());
        user.setStatus(1);
        user.setBalance(2000);
        user.setCreateTime(DateTime.now());
        user.setUpdateTime(DateTime.now());
        int line=userMapper.insert(user);
        System.out.println("line="+line);
    }
    
插入的结果
JDBC Connection [HikariProxyConnection@1768142988 wrapping com.mysql.cj.jdbc.ConnectionImpl@ab24484] will not be managed by Spring
==>  Preparing: INSERT INTO user ( username, password, info, status, balance, create_time, update_time ) VALUES ( ?, ?, ?, ?, ?, ?, ? )
==> Parameters: 张三(String), 13900112224(String), {"age":29,"intro":"伏地魔","gender":"male"}(String), 1(Integer), 2000(Integer), 2023-09-02 22:29:44.733(Timestamp), 2023-09-02 22:29:44.734(Timestamp)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@28369db0]
line=1


在这里插入图片描述

 查询指定的id的
 @Test
    void test2(){
        //查询get 或者是select 找对应的关键词就行
       User user= userMapper.selectById(1674613593516095922L);
        System.out.println("user="+user.toString());
    }
    
    
结果
JDBC Connection [HikariProxyConnection@2123492724 wrapping com.mysql.cj.jdbc.ConnectionImpl@3878be7b] will not be managed by Spring
==>  Preparing: SELECT id,username,password,phone,info,status,balance,create_time,update_time FROM user WHERE id=?
==> Parameters: 1674613593516095922(Long)
<==    Columns: id, username, password, phone, info, status, balance, create_time, update_time
<==        Row: 1674613593516095922, 张三, 13900112224, null, <<BLOB>>, 1, 2000, 2023-09-02 22:29:45, 2023-09-02 22:29:45
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@31b7d869]
user=User(id=1674613593516095922, username=张三, password=13900112224, phone=null, info={"age": 29, "intro": "伏地魔", "gender": "male"}, status=1, balance=2000, createTime=Sat Sep 02 22:29:45 CST 2023, updateTime=Sat Sep 02 22:29:45 CST 2023)


批量查询
    @Test
    void test3(){
        //批量查询 需要传入一个集合数组
        List<Long> ids=new ArrayList<Long>();
        ids.add(1L);
        ids.add(2L);
        ids.add(3L);

        List<User> users= userMapper.selectBatchIds(ids);
        System.out.println("users="+users.toString());
    }

查询结果
==>  Preparing: SELECT id,username,password,phone,info,status,balance,create_time,update_time FROM user WHERE id IN ( ? , ? , ? )
==> Parameters: 1(Long), 2(Long), 3(Long)
<==    Columns: id, username, password, phone, info, status, balance, create_time, update_time
<==        Row: 1, Jack, 123, 13900112224, <<BLOB>>, 1, 1600, 2023-05-19 20:50:21, 2023-06-19 20:50:21
<==        Row: 2, Rose, 123, 13900112223, <<BLOB>>, 1, 300, 2023-05-19 21:00:23, 2023-06-19 21:00:23
<==        Row: 3, Hope, 123, 13900112222, <<BLOB>>, 1, 100000, 2023-06-19 22:37:44, 2023-06-19 22:37:44
<==      Total: 3
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@7cfb4736]
users=[User(id=1, username=Jack, password=123, phone=13900112224, info={"age": 20, "intro": "佛系青年", "gender": "male"}, status=1, balance=1600, createTime=Fri May 19 20:50:21 CST 2023, updateTime=Mon Jun 19 20:50:21 CST 2023), User(id=2, username=Rose, password=123, phone=13900112223, info={"age": 19, "intro": "青涩少女", "gender": "female"}, status=1, balance=300, createTime=Fri May 19 21:00:23 CST 2023, updateTime=Mon Jun 19 21:00:23 CST 2023), User(id=3, username=Hope, password=123, phone=13900112222, info={"age": 25, "intro": "上进青年", "gender": "male"}, status=1, balance=100000, createTime=Mon Jun 19 22:37:44 CST 2023, updateTime=Mon Jun 19 22:37:44 CST 2023)]
2023-09-02 22:36:10.393  INFO 25320 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2023-09-02 22:36:10.400  INFO 25320 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.


    @Test
    void test4(){

        //userMapper.update()

        //userMapper.updateById() 传入的对象必须要有id 改变的是非空的字段的内容 要是不天写的话就是不能更新成功的
        User user=new User();
        user.setUsername("张三修改");
        userMapper.updateById(user);
    }

    @Test
    void test5(){
        User user=new User();
        user.setId(1674613593516095922L);
        user.setUsername("张三修改");
        userMapper.updateById(user);

    }
    
    
test4是更新失败的,但是test5是可以更新成功的。

JDBC Connection [HikariProxyConnection@1456250665 wrapping com.mysql.cj.jdbc.ConnectionImpl@535b1ae6] will not be managed by Spring
==>  Preparing: UPDATE user SET username=? WHERE id=?
==> Parameters: 张三修改(String), 1674613593516095922(Long)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@d08edc5]
userMapper.update()
第一个参数是实体对象。第二个参数是我们需要进行的更新的查询到参数

@Test
    void  test6(){
        //下面是常见的几种删除的操作

        //根据wrapper查询条件进行删除
       // int i =userMapper.delete()

        //批量删除 传入的是一个id的集合对象
        //userMapper.deleteBatchIds()

        //传入的是user对象需要有id的属性
        //userMapper.deleteById()

        //根据的是传入的map的键值对找到指定的数据进行删除的和wrapper是相似的
        //userMapper.deleteByMap()

        //上面的返回值全是int类型的也就是删除的条数的数据

        List<Long> ids=new ArrayList<Long>();
        ids.add(1674613593516095922L);
        int line =userMapper.deleteBatchIds(ids);
        System.out.println("删除的条数="+line);

    }
    
   
删除的操作
JDBC Connection [HikariProxyConnection@1830984476 wrapping com.mysql.cj.jdbc.ConnectionImpl@6f825516] will not be managed by Spring
==>  Preparing: DELETE FROM user WHERE id IN ( ? )
==> Parameters: 1674613593516095922(Long)
<==    Updates: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@5034f5dd]
删除的条数=1

猜你喜欢

转载自blog.csdn.net/weixin_41957626/article/details/132792416