MyBatis-Plus學習筆記(1):環境搭建以及基本的CRUD操做

MyBatis-Plus是一個 MyBatis的加強工具,在 MyBatis 的基礎上只作加強不作改變,使用MyBatis-Plus時,不會影響原來Mybatis方式的使用。html

SpringBoot+MyBatis-Plus環境搭建

SQL腳本:java

CREATE TABLE `tb_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `real_name` varchar(20) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `phone` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO tb_user (real_name,email,phone) VALUES ('小花','cf1@qq.com','18711111111');
INSERT INTO tb_user (real_name,email,phone) VALUES ('小菊','cf2@qq.com','18322222222');
INSERT INTO tb_user (real_name,email,phone) VALUES ('小熊','cf3@qq.com','18133333333');
INSERT INTO tb_user (real_name,email,phone) VALUES ('小虎','cf4@qq.com','18344444444');
INSERT INTO tb_user (real_name,email,phone) VALUES ('小豬','cf5@qq.com','18723232323');

添加依賴以下(不須要額外添加Mybatis的依賴):mysql

<dependencies>
        <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>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.1.tmp</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
</dependencies>

application.yml:spring

spring:
  datasource:
    url: jdbc:mysql://localhost/plusdb?useUnicode=true&characterEncoding=UTF-8
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver

#在控制檯打印SQL語句,com.cf.mpdm.mapper爲存放mapper接口的包名
logging:
  level:
    com.cf.mpdm.mapper: debug

主程序類:sql

package com.cf.mpdm;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

//指定掃描mapper接口的包路徑
@MapperScan("com.cf.mpdm.mapper")
@SpringBootApplication
public class MpdmApplication {

    public static void main(String[] args) {
        SpringApplication.run(MpdmApplication.class, args);
    }

}

UserMapper接口:api

package com.cf.mpdm.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.cf.mpdm.entity.User;

public interface UserMapper extends BaseMapper<User> {
}

UserMapper接口須要繼承BaseMapper接口,而且指定泛型爲表對應的實體類。springboot

實體類User:mybatis

package com.cf.mpdm.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;

//表名tb_user帶tb_前綴,和實體類類名User不匹配,因此須要使用@TableName指定表名
@TableName("tb_user")
public class User {

    //指定主鍵生成策略爲自動增加
    @TableId(type = IdType.AUTO)
    private Integer id;

    private String realName;

    private String email;

    private String phone;

   //get/set ...
}

MyBatis-Plus默認使用下劃線命名到駝峯命名的映射規則來處理表和實體類類名以及表的列名和實體類字段的映射。當默認規則不適用時,則須要經過額外的配置來處理映射,如能夠使用註解@TableName來指定表名,使用@TableId和@TableField來指定主鍵列和非主鍵列的列名。app

@TableId還能夠指定主鍵的生成策略,默認生成策略爲NONE,表示無狀態,未設置主鍵類型。其餘策略詳見IdTypeide

當多數表具備相同的前綴或者相同的主鍵生成策略時,能夠使用全局配置指定表前綴和主鍵策略,而無需一個個手動添加註解,固然少數特殊的仍是能夠經過註解的方式來指定,application.yml:

mybatis-plus:
  global-config:
    db-config:
      # 指定主鍵生成策略爲自動增加
      idType: AUTO
      # 指定表前綴
      tablePrefix: tb_

基本的CRUD操做

package com.cf.mpdm;

import com.cf.mpdm.entity.User;
import com.cf.mpdm.mapper.UserMapper;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SpringBootTest
class MpdmApplicationTests {
    @Autowired
    private UserMapper userMapper;

    @Test
    public void testInsert(){
        //INSERT INTO tb_user ( real_name, email, phone ) VALUES ( ?, ?, ? )
        User user = new User();
        user.setRealName("小蘭");
        user.setEmail("xiaolan@qq.com");
        user.setPhone("18700000000");
        userMapper.insert(user);

            //插入成功時,默認會將主鍵的值回寫到實體類中去
        System.out.println(user.getId());
    }

    @Test
    public void testDelete(){
        //根據主鍵ID刪除記錄
        //DELETE FROM tb_user WHERE id=?
        userMapper.deleteById(6);

        //根據id列表批量刪除記錄
        //DELETE FROM tb_user WHERE id IN ( ? , ? )
        /*List<Integer> idList = new ArrayList<>();
        idList.add(12);
        idList.add(13);
        userMapper.deleteBatchIds(idList);*/

        //根據條件來刪除記錄,如根據real_name來刪除記錄,columnMap的Key必須爲表中的字段名,而不是實體類中的字段名。
        //DELETE FROM tb_user WHERE real_name = ?
        /*Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("real_name", "小花");
        userMapper.deleteByMap(columnMap);*/
    }

    @Test
    public void testUpdate(){
        //根據主鍵id更新記錄
        //UPDATE tb_user SET real_name=? WHERE id=?
        User user = new User();
        user.setId(2);
        user.setRealName("歐皓辰");
        userMapper.updateById(user);
    }

    @Test
    public void testSelect(){
        //根據主鍵id查詢記錄
        //SELECT id,real_name,email,phone FROM tb_user WHERE id=?
        /*User user = userMapper.selectById(3);
        System.out.println(user.getRealName());*/

        //根據id列表查詢對應記錄
        //SELECT id,real_name,email,phone FROM tb_user WHERE id IN ( ? , ? )
        /*List<Integer> idList = new ArrayList<>();
        idList.add(3);
        idList.add(4);
        List<User> userList = userMapper.selectBatchIds(idList);
        System.out.println(userList.size());*/

        //根據條件來查詢對應記錄
        //SELECT id,real_name,email,phone FROM tb_user WHERE real_name = ?
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("real_name", "小蘭");
        List<User> userList = userMapper.selectByMap(columnMap);
        System.out.println(userList.size());
    }
}

關於使用mapper.xml的一些配置

mybatis-plus:
  #指定Mapper所對應的XML文件位置
  mapperLocations: classpath:mapper/*.xml
  #指定別名包掃描路徑,經過該屬性能夠給包中的類註冊別名,註冊後在 Mapper 對應的 XML 文件中能夠直接使用類名,而不用使用全限定的類名
  typeAliasesPackage: com.cf.mpdm.entity
相關文章
相關標籤/搜索