Mybatis-Plus系列--自定义SQL

其他网址

mybatis-plus之自定义sql、分页、Wrapper_CDN-CSDN博客_mybatisplus wrapper分页
Mybatisplus 自定义sql 使用条件构造器 - 静水165 - 博客园

简介

自定义的sql使用Wrapper对版本有要求:mybatis-plus版本需要大于或等于3.0.7。

含义
ew.customSqlSegment 条件构造器(Wrapper)
ew.sqlSet 所设置的列
ew.sqlSelect 要select的列

包里边定义好的常量。我们可以直接用这些常量。

mybatis-plus-core-3.3.2.jar\com\baomidou\mybatisplus\core\toolkit\Constants.class

package com.baomidou.mybatisplus.core.toolkit;

public interface Constants extends StringPool {
    String MYBATIS_PLUS = "mybatis-plus";
    String MD5 = "MD5";
    String AES = "AES";
    String AES_CBC_CIPHER = "AES/CBC/PKCS5Padding";
    String ENTITY = "et";
    String ENTITY_DOT = "et.";
    String WRAPPER = "ew";
    String WRAPPER_DOT = "ew.";
    String WRAPPER_ENTITY = "ew.entity";
    String WRAPPER_SQLSEGMENT = "ew.sqlSegment";
    String WRAPPER_EMPTYOFNORMAL = "ew.emptyOfNormal";
    String WRAPPER_NONEMPTYOFNORMAL = "ew.nonEmptyOfNormal";
    String WRAPPER_NONEMPTYOFENTITY = "ew.nonEmptyOfEntity";
    String WRAPPER_EMPTYOFWHERE = "ew.emptyOfWhere";
    String WRAPPER_NONEMPTYOFWHERE = "ew.nonEmptyOfWhere";
    String WRAPPER_ENTITY_DOT = "ew.entity.";
    String U_WRAPPER_SQL_SET = "ew.sqlSet";
    String Q_WRAPPER_SQL_SELECT = "ew.sqlSelect";
    String Q_WRAPPER_SQL_COMMENT = "ew.sqlComment";
    String Q_WRAPPER_SQL_FIRST = "ew.sqlFirst";
    String COLUMN_MAP = "cm";
    String COLUMN_MAP_IS_EMPTY = "cm.isEmpty";
    String COLLECTION = "coll";
    String WHERE = "WHERE";
    String MP_OPTLOCK_INTERCEPTOR = "oli";
    String MP_OPTLOCK_VERSION_ORIGINAL = "MP_OPTLOCK_VERSION_ORIGINAL";
    String MP_OPTLOCK_VERSION_COLUMN = "MP_OPTLOCK_VERSION_COLUMN";
    String MP_OPTLOCK_ET_ORIGINAL = "MP_OPTLOCK_ET_ORIGINAL";
    String WRAPPER_PARAM = "MPGENVAL";
    String WRAPPER_PARAM_FORMAT = "#{%s.paramNameValuePairs.%s}";
}

实例代码

本项目所有源码:https://gitee.com/shapeless/demo_MybtisPlus/tree/master/Complex

entity

package com.example.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;

@Data
@TableName(value = "tb_user")//指定表名
public class User{
    //value与数据库主键列名一致,若实体类属性名与表主键列名一致可省略value
    @TableId(value = "id",type = IdType.ASSIGN_UUID)//指定自增策略
    private String id;
    private String name;

    //若没有开启驼峰命名,或者表中列名不符合驼峰规则,可通过该注解指定数据库表中的列名,exist标明数据表中有没有对应列
    @TableField(value = "last_name",exist = true)
    private String lastName;
    private String email;
    private Integer gender;
    private Integer age;
}

mapper

package com.example.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.entity.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

@Repository
public interface UserMapper extends BaseMapper {
    @Select("select * from tb_user ${ew.customSqlSegment}")
    List testSelect1(@Param("ew") Wrapper wrapper);
//    List testSelect1(@Param(Constants.WRAPPER) Wrapper wrapper);

    @Select("select * from ${table_name} ${ew.customSqlSegment}")
    List testSelect2(@Param("table_name")String tableName, @Param("ew") Wrapper wrapper);

    @Select("select ${ew.SqlSelect} from ${table_name} ${ew.customSqlSegment}")
    List testSelect3(@Param("table_name")String tableName, @Param("ew") Wrapper wrapper);

    @Select("select ${ew.SqlSelect} from ${table_name} ${ew.customSqlSegment}")
    List> testSelect4(@Param("table_name")String tableName, @Param("ew") Wrapper wrapper);

    @Select("select * from ${table_name} where age = #{age}")
    List testSelect5(@Param("table_name")String tableName,  @Param("age")Integer age);

    @Select("select ${ew.SqlSelect} from ${table_name} where age = #{age} ${ew.customSqlSegment}")
    List testSelect6(@Param("table_name")String tableName,  @Param("age")Integer age,@Param("ew") Wrapper wrapper);

    @Select("select * from ${table_name} ${ew.customSqlSegment}")
    User testSelect7(@Param("table_name")String tableName,  @Param("ew") Wrapper wrapper);

    //只取name这一列
    @Select("SELECT tb_user.name FROM tb_user ${ew.customSqlSegment}")
    List getNames(@Param("ew") Wrapper wrapper);

    @Update("update ${table_name} set ${ew.sqlSet} ${ew.customSqlSegment}")
    int testUpdate1(@Param("table_name")String tableName, @Param("ew") Wrapper wrapper);
}
 
  

实例测试

测试代码

package com.example;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import org.junit.jupiter.api.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.List;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
class CustomSqlTests {
    @Autowired
    UserMapper userMapper;

    @Test
    public void insert() {
        User user = new User();
        for (int i = 0; i < 10; i++) {
            user.setId(String.valueOf(i));
            user.setName("Iron Man" + i);
            if (i < 5) {
                user.setAge(20);
            } else {
                user.setAge(23);
            }
            userMapper.insert(user);
        }
    }

    @Test
    public void mySqlTest123() {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", "张三");
        queryWrapper.eq("age", 20);
        queryWrapper.eq("last_name", null);
        queryWrapper.select("id", "age");
//        List users = userMapper.testSelect1(queryWrapper);
//        List users = userMapper.testSelect2("tb_user", queryWrapper);
        List users = userMapper.testSelect3("tb_user", queryWrapper);

        users.forEach(System.out::println);
    }

    @Test
    public void mySqlTest4() {
        QueryWrapper queryWrapper = new QueryWrapper<>();

        queryWrapper.select("id", "age");
        List> mapList = userMapper.testSelect4("tb_user", queryWrapper);

        mapList.forEach(System.out::println);
    }

    @Test
    public void mySqlTest56() {
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", "张三").eq("last_name", null);
        queryWrapper.select("id", "age");
//        List userList = userMapper.testSelect5("tb_user", 28);
        List userList = userMapper.testSelect6("tb_user", 28, queryWrapper);

        userList.forEach(System.out::println);
    }

    @Test
    public void mySqlTest7() {
        QueryWrapper queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("age", "20");
        queryWrapper.eq("name", "Iron Man1");
        User user = userMapper.testSelect7("tb_user", queryWrapper);

        System.out.println(user);
    }

    @Test
    public void getNames() {
        QueryWrapper objectQueryWrapper = new QueryWrapper<>()
                .eq("age", 20);
        List names = this.userMapper.getNames(objectQueryWrapper);
        System.out.println(names);
    }
} 
  

测试结果

mySqlTest123测试结果

testSelect1/ testSelect2结果

==>  Preparing: select * from tb_user WHERE (name = ? AND age = ? AND last_name = ?) 
==> Parameters: 张三(String), 28(Integer), null
<==      Total: 0

 testSelect3结果

==>  Preparing: select id,age from tb_user WHERE (name = ? AND age = ? AND last_name = ?) 
==> Parameters: 张三(String), 28(Integer), null
<==      Total: 0

mySqlTest4测试结果(成功:返回List>)

==>  Preparing: select id,age from tb_user 
==> Parameters: 
<==    Columns: id, age
<==        Row: 321eece6b1620ab97123785edbdef490, 20
<==        Row: 101eece6b1620ab97ffa8c8edbdef490, 20
<==        Row: 9d532cbadd8ea0beb7ea5a7c867bc863, 20
<==      Total: 3
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@43f9dd56]
{id=321eece6b1620ab97123785edbdef490, age=20}
{id=101eece6b1620ab97ffa8c8edbdef490, age=20}
{id=9d532cbadd8ea0beb7ea5a7c867bc863, age=20}

mySqlTest56测试结果

testSelect5(通过#{}传列的值)

==>  Preparing: select * from tb_user where age = ? 
==> Parameters: 28(Integer)
<==      Total: 0

 testSelect6(报错(既使用where又使用Wrapper))

==>  Preparing: select id,age from tb_user where age = ? WHERE (name = ? AND last_name = ?) 
==> Parameters: 28(Integer), 张三(String), null

mySqlTest7测试结果(只取一个。若返回只有一个则成功,否则报错)

返回1个赋值给1个(成功)

==>  Preparing: select * from tb_user WHERE (name = ?) 
==> Parameters: Iron Man1(String)
<==    Columns: id, name, last_name, email, gender, age
<==        Row: 1, Iron Man1, null, null, null, 20
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@4ba6ec50]
User(id=1, name=Iron Man1, lastName=null, email=null, gender=null, age=20)

返回多个赋值给1个(失败

==>  Preparing: select * from tb_user WHERE (age = ?) 
==> Parameters: 20(String)
<==    Columns: id, name, last_name, email, gender, age
<==        Row: 321eece6b1620ab97123785edbdef490, null, 东方不败, [email protected], 1, 20
<==        Row: 101eece6b1620ab97ffa8c8edbdef490, null, Tony, [email protected], 1, 20
<==        Row: 9d532cbadd8ea0beb7ea5a7c867bc863, null, Pepper, [email protected], 2, 20
<==        Row: 0, Iron Man0, null, null, null, 20
<==        Row: 1, Iron Man1, null, null, null, 20
<==        Row: 2, Iron Man2, null, null, null, 20
<==        Row: 3, Iron Man3, null, null, null, 20
<==        Row: 4, Iron Man4, null, null, null, 20
<==      Total: 8
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@76464795]


org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 8

getNames测试结果

==>  Preparing: SELECT tb_user.name FROM tb_user WHERE (age = ?) 
==> Parameters: 20(Integer)
<==    Columns: name
<==        Row: Iron Man0
<==        Row: Iron Man1
<==        Row: Iron Man2
<==        Row: Iron Man3
<==        Row: Iron Man4
<==      Total: 5
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@59b65dce]
[Iron Man0, Iron Man1, Iron Man2, Iron Man3, Iron Man4]

你可能感兴趣的:(Mybatis-Plus系列--自定义SQL)