SpringBoot整合Mybatis-Plus

SpringBoot整合Mybatis-Plus

Mybatis-Plus 官网: https://baomidou.oschina.io/mybatis-plus-doc/#/spring-boot

一,pom引入:

<dependencies>
  <dependency>
      <groupId>com.baomidougroupId>
      <artifactId>mybatis-plus-boot-starterartifactId>
      <version>最新版本号version>
  dependency>
dependencies>

<build>
  <resources>
      <resource>
          <directory>src/main/javadirectory>
          <filtering>falsefiltering>
          <includes>
              <include>**/mapper/*.xmlinclude>
          includes>
      resource>
  resources>
build>

引入mybatis-plus后,mybatis,mybatis-spring不需要再引入

二,application.yml:

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mall?characterEncoding=utf-8&serverTimezone=GMT%2B8
    username: root
    password: 123456
#    driver-class-name: com.mysql.cj.jdbc.Driver
server:
  port: 8181
mybatis-plus:
#  mapper-locations: classpath*:/mapper/**Mapper.xml
#  #实体扫描,多个package用逗号或者分号分隔
#  typeAliasesPackage: com.tdx.account_service.entity
  global-config:
    #主键类型  0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
    id-type: 0
    #字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
    field-strategy: 2
    #驼峰下划线转换
    db-column-underline: true
    #刷新mapper 调试神器
    refresh-mapper: true
    #数据库大写下划线转换
    #capital-mode: true
    #序列接口实现类配置
    #key-generator: com.baomidou.springboot.xxx
    #逻辑删除配置(下面3个配置)
    logic-delete-value: 0
    logic-not-delete-value: 1
    #自定义SQL注入器
    #sql-injector: com.baomidou.mybatisplus.mapper.LogicSqlInjector
    #自定义填充策略接口实现
    #meta-object-handler: com.baomidou.springboot.xxx
  configuration:
    map-underscore-to-camel-case: true
    cache-enabled: false
    # 是否将sql打印到控制面板(该配置会将sql语句和查询的结果都打印到控制台)
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

三,实体层

表名:

表名不一致需指定:通过实体类上加注解

@TableName(value = “admin”)

主键:

要标注主键和策略。否则会引起错误。也可以再配置文件内做全局处理

如果表主键名和实体主键名不一样,则需指定主键名 。

@TableId(value=“id”,type = IdType.AUTO) //主键自增策略

@TableName(value = "admin")  //表名和实体不一致时需指明,一致可省略
@Data  //:注解在类上,等同于@Getter、@Setter、@RequiredArgsConstructor、@ToString和@EqualsAndHashCode一起的效果 ---需要引入lombok和安装lombok插件
public class Admin extends Model<Admin> {
    @TableId(type = IdType.AUTO)  //主键自增策略
    private Integer id;  
    private String username;
    @TableLogic //逻辑删除注解
    private Integer status;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date createdate;

时间格式化

	@DateTimeFormat(pattern = "yyyy-MM-dd")
    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date createdate;

四,持久层

1. Mybatis-Plus启动注入SQL原理

SqlSessionFactory => Configuration => MappedStatements

每一个mappedStatement 都表示 Mapper接口中的一个方法与Mapper映射文件中的一个SQL

MP在启动就会分析每个xxxMapper中的方法,并且讲对应的SQL语句处理好,保存到configuration对象内mappedStatements中。

2. 需继承BaseMapper,基本CRUD不用写

public interface AdminDao extends BaseMapper<Admin> {

}
BaseMapper 自带CRUD方法
public interface BaseMapper<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);
 	//根据Map条件查询
    List<T> selectByMap(@Param("cm") Map<String, Object> columnMap);
	//查询一个对象
    T selectOne(@Param("ew") Wrapper<T> queryWrapper);
	//记录查询数量
    Integer selectCount(@Param("ew") Wrapper<T> queryWrapper);
	//使用Wrapper对象作为查询条件
    List<T> selectList(@Param("ew") Wrapper<T> queryWrapper);
	//根据Map条件查询
    List<Map<String, Object>> selectMaps(@Param("ew") Wrapper<T> queryWrapper);

    List<Object> selectObjs(@Param("ew") Wrapper<T> queryWrapper);
	//根据Wrapper条件并进行分页   page:分页查询条件  Wrapper:条件构造器
    IPage<T> selectPage(IPage<T> page, @Param("ew") Wrapper<T> queryWrapper);

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

3. INSERT

insert:返回受影响的行数

@Test
    public void insert(){
        Admin admin =new Admin();
        admin.setStatus(1);
        admin.setUsername("mybatis-plus-insert");
        admin.setCreatedate(new Date());
        int i = adminDao.insert(admin);
        // 主键是id,获取新添加记录的id,使用对象的getId()
        int newId = admin.getId();
        System.out.println(i+"新增加的ID是:"+newId);
    }

4. UPDATE

updateById:

根据主键修改,返回受影响的行数

注意:MP判断是否修改字段是判断属性的null,最好实体类Student的属性都是引用类型, 包括Integer status, 这样不给status赋值,就不会更新status字段。如果实体类定义 int status 。 修改结果是 status 是 0 , 因为status 属性 int status ,这样定义int类型默认初值是 0 。

//根据主键修改对象
    @Test
    public void testUpdateAdmin(){
        Admin admin =new Admin();
        admin.setId(3);
        admin.setUsername("新的名字");
        admin.setStatus(1);
        //根据主键修改对象, 对象null的属性,不进行修改
        int rows = adminDao.updateById(admin);
    }

5. DELETE:

 //删除
 deleteBatchIds(Collection); //参数是主键的集合,删除多条数据
 delete(Wrapper); //根据Wrapper对象的条件,删除数据
 deleteById(id);//根据单一主键,删除数据
 deleteByMap(Map); //使用Map作为条件删除数据

deleteById:

根据主键删除,返回受影响的行数

//删除数据
    @Test
    public void testDeleteAdmin(){
        // sql : DELETE FROM admin WHERE id=?
        int rows = adminDao.deleteById(2);
        System.out.println("deleteById结果:"+rows);
    }

deleteByMap:

删除指定条件的数据,返回受影响的行数

创建Map, 添加条件数据。Map的key是字段名,value是字段的值。调用deleteByMap(); 传入Map对象。 返回值成功删除的行数。

@Test
    public void testDeleteAdminMap(){
        Map<String,Object> condition = new HashMap<>();
        condition.put("username","新的名字");
        condition.put("status",1);
        int rows = adminDao.deleteByMap(condition);
        System.out.println("deleteByMap 受影响的行数:"+rows);
    }

6. SELECT

  //查询
  // 查询集合中多个主键值数据
  List<T> selectBatchIds(@Param("coll") Collection<? extends Serializable> idList);
  //根据Map条件查询
  List<T> selectByMap(@Param("cm") Map<String, Object> columnMap); 
  //使用Wrapper对象作为查询条件
  List<T> selectList(@Param("ew") Wrapper<T> queryWrapper); 
  //根据主键值查询
  T selectById(Serializable id); 
  //根据Wrapper条件并进行分页
  IPage<T> selectPage(IPage<T> page, @Param("ew") Wrapper<T> queryWrapper); 
  //记录查询数量
  Integer selectCount(@Param("ew") Wrapper<T> queryWrapper); 
  //查询一个对象
  T selectOne(@Param("ew") Wrapper<T> queryWrapper);

selectOne

sql: select * from admin where id =3

先创建Wrapper对象,添加查询条件, 调用selectOne()方法。 selectOne()的查询结果必须小于或等于一条记录,MP内部是调用的MyBatis的selectOne()方法,多于一个记录,系统会报错

@Test
    public void selectOne(){
        QueryWrapper<Admin> condition = new QueryWrapper<>();
        condition.eq("id","3");
        Admin res = adminDao.selectOne(condition);
        System.out.println(res.toString());
    }

selectById

sql: select * from admin where id =3

@Testpublic void testSelectAdmin(){
    Admin admin = adminDao.selectById(3);
    System.out.println("根据id查询结果:"+admin.toString());
}

selectBatchIds

sql: select * from admin where id in (1,4)

@Test
    public void selectBatchIds(){
        List<Integer> idlist =new ArrayList<>();
        idlist.add(1);
        idlist.add(4);
        List<Admin> res  = adminDao.selectBatchIds(idlist);
        System.out.println(res.size());
    }

selectByMap

sql: select * from admin where username=“admin” and status=1

@Test
    public void selectByMap(){
        Map<String,Object> columnMap = new HashMap<>();
        columnMap.put("username","admin");
        columnMap.put("status",1);
        List<Admin> res  = adminDao.selectByMap(columnMap);
        System.out.println(res.toString());
    }

selectPage :分页查询

需先配置分页bean

package com.xxx.xxx.config;

import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisPlusConfiguration {
    /**
     * 开启mybatis-plus分页功能
     * @return
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

selectPage(IPage page, Wrapper queryWrapper)

@Test
    public void selectPageQueryWrapper(){
        //new QueryWrapper() 条件构造器
        //SELECT id,username,status,createdate FROM admin WHERE status=0 AND createDate BETWEEN ? AND ? AND status = ? LIMIT ?,? 
        //分页查询
        IPage backIPage = adminDao.selectPage(new Page<Admin>(3,4),
                new QueryWrapper<Admin>().between("createDate","2020-2-21","2020-2-23")
                        .eq("status",0));
        System.out.println("当前页数数据条数"+backIPage.getSize());
        System.out.println("总页数"+backIPage.getPages());
        System.out.println("总数据条数"+backIPage.getTotal());
        System.out.println("当前页数"+backIPage.getCurrent());
        for (Admin admin:(List<Admin>)backIPage.getRecords()) {
            System.out.println(admin.toString());
        }
    }

sql: SELECT id,username,status,createdate FROM admin WHERE status=0 LIMIT ?,?

@Test
    public void selectPage(){
        //分页查询  Page(2,3)  第二页,三条数据 ;  null 无筛选条件
        IPage backIPage = adminDao.selectPage(new Page<Admin>(2,3),null);
        System.out.println("当前页数数据条数"+backIPage.getSize());
        System.out.println("总页数"+backIPage.getPages());
        System.out.println("总数据条数"+backIPage.getTotal());
        System.out.println("当前页数"+backIPage.getCurrent());
        List<Admin> list = backIPage.getRecords();
        for (Admin a:list){
            System.out.println(a.toString());
        }
    }

7. 逻辑删除

yml配置:
mybatis-plus:
  global-config:
    #逻辑删除配置(下面2个配置 还有配置一个bean,实体指定逻辑删除字段)
    logic-delete-value: 0
    logic-not-delete-value: 1
实体字段配置:
@TableLogic //逻辑删除注解
    private Integer status;
bean配置:
package com.xxx.xxx.config;

import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import com.baomidou.mybatisplus.extension.injector.LogicSqlInjector;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MyBatisPlusConfiguration {
     /**
     * 逻辑删除
     * @return
     */
    @Bean
    public ISqlInjector sqlInjector() {
        return new LogicSqlInjector();
    }
}

执行效果:
//删除数据
    @Test
    public void deleteById(){
        // sql : DELETE FROM admin WHERE id=?  
        //===>UPDATE admin SET status=1 WHERE id=? AND status=0 
        int rows = adminDao.deleteById(11);
        System.out.println("deleteById结果:"+rows);
    } 

五,条件构造器 EntityWrapper

  1. Mybatis-Plust通过ENtityWrapper或者Condition来让用户自由的构建查询条件,简单便捷,没有额外的负担,能够有效提高开发效率

  2. 实体包装器,主要用于处理sql拼接,排序,实体参数查询等

  3. 注意:使用的是数据库阻断,不是java属性

  4. 条件参数说明:

    https://mp.baomidou.com/guide/wrapper.html#abstractwrapper

以下示例中备注 * 代表表全字段名

between / eq:

@Test
    public void selectPageQueryWrapper(){
        //new QueryWrapper() 条件构造器
        //分页查询
        //SELECT id,username,status,createdate FROM admin WHERE createDate BETWEEN ? AND ? AND status = ?
        IPage backIPage = adminDao.selectPage(new Page<Admin>(3,4),
                new QueryWrapper<Admin>().between("createDate","2020-2-21","2020-2-23")
                        .eq("status",0));
        //getRecords()得到的是所有行信息,不是分页的内容
        for (Admin admin:(List<Admin>)backIPage.getRecords()) {
            System.out.println(admin.toString());
        }
    }

or :

@Test
    public void selectListQueryWrapper(){
        //SELECT * FROM news WHERE status = ? AND title LIKE ? OR author LIKE ? 
        List<News> list = newsDao.selectList(
                new QueryWrapper<News>()
                        .eq("status",1)
                        .like("title","上海")
                .or()   
                .like("author","上海")
        );
    }

update:

@Test
    public void updateQueryWrapper(){
        //UPDATE news SET author=? WHERE status = ? AND title LIKE ? 
        News news =new News();
        news.setId(1);//设置主键Id是没有用的,执行会根据QueryWrapper条件更新所有满足条件的行
        news.setAuthor("上海1");
         newsDao.update(news,
                new QueryWrapper<News>()
                        .eq("status",0)
                        .like("title","上海")
        );
    }

delete:

@Test
    public void deleteQueryWrapper(){
        //DELETE FROM admin WHERE id = ? 
        adminDao.delete(
                new QueryWrapper<Admin>()
                        .eq("id",28)
        );
    }

orderBy:

@Test
    public void selectListOrderByQueryWrapper(){
        //SELECT * FROM news WHERE status = ? ORDER BY readNum DESC
        List<News> list = newsDao.selectList(
                new QueryWrapper<News>()
                        .eq("status",1)
                        .orderByDesc("readNum")
        );
    }

六,ActiveRecord(活动记录)

AR基本CRUD

insert:

insert
@Test
    public void insertAR(){
        //INSERT INTO admin ( username, status, createdate ) VALUES ( ?, ?, ? ) 
        Admin admin =new Admin();
        admin.setStatus(0);
        admin.setUsername("AR新增");
        admin.setCreatedate(new Date());
        boolean res = admin.insert();
        if(res){
            int newId = admin.getId();
            System.out.println("AR新增加的ID是:"+newId);
        }else{
            System.out.println("AR新增失败");
        }

update:

updateById
@Test
    public void updateAR(){
        //UPDATE admin SET username=?, createdate=? WHERE id=?
        Admin admin =new Admin();
        admin.setId(29);
        admin.setUsername("AR修改");
        admin.setCreatedate(new Date());
        boolean res = admin.updateById();
        if(res){
            System.out.println("AR修改成功");
        }else{
            System.out.println("AR修改失败");
        }
    }

select:

selectById(Serializable id)
@Test
    public void selectByIdAR(){
        //SELECT id,username,status,createdate FROM admin WHERE id=? 
        Admin admin = new Admin();
        Admin res = admin.selectById(30);
        System.out.println(res.toString());
    }
selectAll()
@Test
    public void selectAllAR(){
        //SELECT id,username,status,createdate FROM admin 
        Admin admin = new Admin();
        List<Admin> res = admin.selectAll();
        for (Admin a : res){
            System.out.println(a.toString());
        }
    }
selectList(Wrapper queryWrapper)

queryWrapper为null查询所有

@Test
    public void selectList(){
        //SELECT id,username,status,createdate FROM admin WHERE status = ? 
        Admin admin = new Admin();
        List<Admin> res = admin.selectList(new QueryWrapper<Admin>().eq("status",1));
        for (Admin a : res){
            System.out.println(a.toString());
        }
    }
selectCount(Wrapper queryWrapper)

queryWrapper为null查询所有

@Test
    public void selectCountAR(){
        //SELECT COUNT( 1 ) FROM admin WHERE status = ?
        Admin admin = new Admin();
        int res = admin.selectCount(new QueryWrapper<Admin>().eq("status",1));
        System.out.println("合计查询数:"+res);
    }
selectPage(IPage page, Wrapper queryWrapper) : AR分页
@Test
    public void selectPageAR(){
        //SELECT id,username,status,createdate FROM admin WHERE status=0 AND status = ? LIMIT ?,? 
        Admin admin = new Admin();
        IPage<Admin> page = admin.selectPage(new Page<>(1,3),new QueryWrapper<Admin>().eq("status",0));
        List<Admin> admins = page.getRecords();
        System.out.println("当前页数数据条数"+page.getSize());
        System.out.println("总页数"+page.getPages());
        System.out.println("总数据条数"+page.getTotal());
        System.out.println("当前页数"+page.getCurrent());
        for (Admin a : admins){
            System.out.println(a.toString());
        }
    }

detele

deleteById
@Test
    public void deleteByIdAR(){
        //DELETE FROM admin WHERE id=?   删除不存在的数据逻辑上是成功的返回也是true
        Admin admin = new Admin();
        boolean res = admin.deleteById(27);
        System.out.println(res);
    }

detele

@Test
    public void deleteAR(){
        //DELETE FROM admin WHERE id=?  删除不存在的数据逻辑上是成功的返回也是true
        Admin admin = new Admin();
        boolean res = admin.delete(new QueryWrapper<Admin>().eq("id",26));
        System.out.println(res);
    }

你可能感兴趣的:(SpringBoot整合Mybatis-Plus)