springboot+mybatis_plus的使用

项目码云地址:https://gitee.com/XiangWenTian001/mybatis_plus

新建user表

CREATE TABLE `user` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `phone` varchar(19) NOT NULL,
  `age` int(3) NOT NULL,
  `address` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=115 DEFAULT CHARSET=utf8;

            com.baomidou
            mybatis-plus-boot-starter
            3.1.0
        

整个pom.xml



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.5.RELEASE
         
    
    com.mybatisplus
    demo
    0.0.1-SNAPSHOT
    demo
    Demo project for Spring Boot

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            mysql
            mysql-connector-java

        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.1.0
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


 

 

 

application.yml中配置mybatis_plus

server:
  port: 8080
spring:
  datasource:
    username: root
    password: 123456
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://125.25.3.39:3306/testdb?characterEncoding=utf-8


mybatis-plus:
  mapper-locations: classpath:/mapper/*Mapper.xml
  typeAliasesPackage: com.mybatisplus.demo.entity
  configuration:
    #配置返回数据库(column下划线命名&&返回java实体是驼峰命名),自动匹配无需as(没开启这个,SQL需要写as: select user_id as userId)
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
      id-type: NONE

实体类  @Data是loombook插件,需要导入相应jar包,可自行学习

@Data
public class User {
    private Integer id;
    private String userName;
    private String password;
    private String address;
    private String phone;
    private Integer age;
}

userMapper中

@Mapper
public interface UserMapper extends BaseMapper {
    
}

userMapper继承了BaseMapper,一些通用的增删该查根本不用我们写了,有些类似于jpa。

多表操作时,个人觉得还是和原始方式一样建立xml文件操作方便点,注解方式不是很明晰。

测试:

package com.mybatisplus.demo;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mybatisplus.demo.dao.UserMapper;
import com.mybatisplus.demo.entity.User;
import com.mybatisplus.demo.vo.UserArticleVo;
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;
import java.util.Map;


/**
 * CREATE TABLE `user` (
 * `id` int(10) NOT NULL AUTO_INCREMENT,
 * `user_name` varchar(255) NOT NULL,
 * `password` varchar(255) NOT NULL,
 * `phone` varchar(19) NOT NULL,
 * `age` int(3) NOT NULL,
 * `address` varchar(255) DEFAULT NULL,
 * PRIMARY KEY (`id`)
 * ) ENGINE=InnoDB AUTO_INCREMENT=65 DEFAULT CHARSET=utf8;
 */


@RunWith(SpringRunner.class)
@SpringBootTest
public class UserMapperTests {
    @Autowired
    private UserMapper userDao;


    /****************************************insert***************************************************************************/

    @Test
    public void testAdd() {
        for (int i = 0; i < 50; i++) {
            User user = new User();
            user.setAddress("杭州市下城区小区路33号==" + i);
            user.setAge(i);
            user.setPassword("admin" + i);
            user.setUserName("admin" + i);
            user.setPhone("18900994378=" + i);
            userDao.insert(user);
        }

    }

    /****************************************update***************************************************************************/
    /**
     * 传值为null不会更新
     */
    @Test
    public void testUpdate1() {
        User user = new User();
        user.setId(17);
        user.setAddress(null);
        user.setAge(129);
        user.setPassword("admin11111");
        user.setUserName("admin1111");
        user.setPhone("18900994378");
        //UPDATE user SET user_name=?, password=?, phone=?, age=? WHERE id=?
        userDao.updateById(user);
    }

    /**
     * 传值为空字符串会更新。
     * pojo一定要设置成包装类,否则更新时会把默认值跟新掉,
     * 如字段age设置成int类型,不传值时会将age更新为0,int默认值为0
     */
    @Test
    public void testUpdate2() {
        User user = new User();
        user.setId(17);
        user.setAddress("");
        user.setAge(129);
        user.setPassword("admin11111");
        user.setUserName("admin1111");
        user.setPhone("18900994378");
        //UPDATE user SET user_name=?, password=?, address=?, phone=?, age=? WHERE id=?
        userDao.updateById(user);
    }


    /**
     * 根据条件更新
     */
    @Test
    public void testUpdateWrapper() {
        User user = new User();
        user.setAddress("update999");
        UpdateWrapper wrapper = new UpdateWrapper<>();
        wrapper.eq("user_name", "admin");
        //UPDATE user SET address=? WHERE user_name = ?
        userDao.update(user, wrapper);
    }

    /****************************************delete***************************************************************************/

    @Test
    public void testDelete() {
        userDao.deleteById(2);
    }


    @Test
    public void testBatchDelete() {
        List list = new ArrayList<>();
        list.add(1);
        list.add(3);
        userDao.deleteBatchIds(list);
    }


    @Test
    public void testMapDelete() {
        Map map = new HashMap<>();
        map.put("age", "1");
        map.put("password", "admin1");
        map.put("user_name", "admin1");
        //DELETE FROM user WHERE password = ? AND user_name = ? AND age = ?
        userDao.deleteByMap(map);
    }

    @Test
    public void testWrapperDelete() {
        //DELETE FROM user WHERE id = ?
        userDao.delete(new UpdateWrapper().eq("id", "64"));
    }
/****************************************select***************************************************************************/
    /**
     * 查询全部
     */
    @Test
    public void testGetAll() {
        //SELECT id,user_name,password,address,phone,age FROM user
        List list = userDao.selectList(null);
        list.stream().forEach(user -> System.out.println(user));
    }


    /**
     * 根据id批量查询
     */
    @Test
    public void testSelectBatchIds() {
        List idList = new ArrayList<>();
        idList.add(11);
        idList.add(32);
        //SELECT id,user_name,password,address,phone,age FROM user WHERE id IN ( ? , ? )   Parameters: 11(Integer), 32(Integer)
        List list = userDao.selectBatchIds(idList);
        list.stream().forEach(user -> System.out.println(user));
    }

    /**
     * map构造条件查询
     */
    @Test
    public void testdSele1ctByMap() {
        Map map = new HashMap<>();
        map.put("id", "44");
        map.put("password", "admin29");
        ////SELECT id,user_name,password,address,phone,age FROM user WHERE password = ? AND id = ?
        List list = userDao.selectByMap(map);
        list.stream().forEach(user -> System.out.println(user));
    }


    /**
     * 实体类构造条件查询
     */
    @Test
    public void testdSelectList1() {
        User user = new User();
        user.setId(44);
        user.setPhone("18900994378=29");
        //SELECT id,user_name,password,address,phone,age FROM user WHERE id=? AND phone=?
        List list = userDao.selectList(new QueryWrapper<>(user));
        list.stream().forEach(u -> System.out.println(u));
    }

    /**
     * QueryWrapper构造条件查询
     */
    @Test
    public void testSeleectList2() {
        List userList = userDao.selectList(
                new QueryWrapper().gt("age", "22")
        );
        //SELECT id,user_name,password,address,phone,age FROM user WHERE age > ?
        userList.stream().forEach(u -> System.out.println(u));
    }


    /**
     * 分页查询,逻辑分页,如果要物理分页需要注入PaginationInterceptor
     */
    @Test
    public void testdSeleectList3() {
        List userList = userDao.selectPage(
                new Page(1L, 8L),
                null
        ).getRecords();
        userList.stream().forEach(u -> System.out.println(u));
    }


    /**
     * 部分字段查询
     */
    @Test
    public void testSelectList() {
        //SELECT id,user_name,password FROM user
        List userList = userDao.selectList(new QueryWrapper().select("id,user_name,password"));
        userList.stream().forEach(user -> System.out.println(user));
    }

    /****************************************多表操作***************************************************************************/
    @Test
    public void testManyTable() {
        Page page = new Page<>(1,7);
        //SELECT u .id AS userId, u .user_name, u .address, u .phone, u .age, a.content, a.title FROM `user` u, article a WHERE u.id = a.user_id LIMIT ?,?
        List list=userDao.getUserArticle(page);
        list.stream().forEach(userArticleVo -> System.out.println(userArticleVo));
    }


}

项目码云地址:https://gitee.com/XiangWenTian001/mybatis_plus

 

你可能感兴趣的:(mybatis_plus)