MyBatis-Plus 简单的查询操作

是对MyBatis-Plus的功能进行简单介绍,虽然是介绍,也让我们领略到他的优雅与强大。你是不是已经被吸引了?别着急,上一节,我们算是参观了MyBatis的风景,这一节,我将带你领略他独特的魅力。

Lambda

官方表示,3.x支持Lambda表达式,那应该怎么使用呢?我们来看个例子:

 

QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
queryWrapper.lambda().eq(Student::getName, "小小");
List<Student> studentList = list(queryWrapper);
for (Student student : studentList){
    Console.info(student);
}

看一下测试结果(为了看好,我们转成json):

{
    "id":1035789714459471874,
    "name":"小小",
    "age":26,
    "info":"无畏造英雄",
    "isDelete":false,
    "createTime":"Sep 1, 2018 3:21:26 PM",
    "updateTime":"Sep 1, 2018 3:21:26 PM",
    "gender":"MALE",
    "idcardId":1035789714388168706,
    "cityId":1035762001753501698
}

如果你使用了我的配置,你也能看到相应的SQL

==>  Preparing: SELECT id,name,age,info,is_delete,create_time,update_time,gender,idcard_id,city_id FROM t_student WHERE name = ? 
==> Parameters: 小小(String)
<==    Columns: id, name, age, info, is_delete, create_time, update_time, gender, idcard_id, city_id
<==        Row: 1035789714459471874, 小小, 26, <<BLOB>>, 0, 2018-09-01 15:21:26.0, 2018-09-01 15:21:26.0, 1, 1035789714388168706, 1035762001753501698
<==      Total: 1

分页查询

感觉哈,分页查询是他们框架的起因,那我们先说分页查询。直接看代码:

第一步:在 Application 中配置

/**
 * 分页插件
 */
@Bean
public PaginationInterceptor paginationInterceptor() {
    return new PaginationInterceptor();
}

å页代ç 

看看 JSON 数据:

{
    "records":[
        {
            "id":1035788325322752001,
            "name":"张飞",
            "age":1,
            "info":"1",
            "isDelete":false,
            "createTime":"Sep 1, 2018 3:15:55 PM",
            "updateTime":"Sep 1, 2018 3:15:55 PM",
            "gender":"MALE",
            "idcardId":1035788325276614657,
            "cityId":1035788325201117185
        },
        {
            "id":1035789714459471874,
            "name":"小小",
            "age":26,
            "info":"无畏造英雄",
            "isDelete":false,
            "createTime":"Sep 1, 2018 3:21:26 PM",
            "updateTime":"Sep 1, 2018 3:21:26 PM",
            "gender":"MALE",
            "idcardId":1035789714388168706,
            "cityId":1035762001753501698
        }
    ],
    "total":2,
    "size":2,
    "current":1,
    "optimizeCountSql":true
}

 

不要问我前端应该怎么写,表示我也不会写。

条件查询

终于要进入这里了,是不是很激动啊。别急,客官,抽根烟先,我们慢慢来。

【1】多eq

QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
queryWrapper.lambda()
        .eq(Student::getName, "西夏")
        .eq(Student::getAge, 26);
List<Student> studentList = list(queryWrapper);
for (Student student : studentList)
    Console.info(new Gson().toJson(student));

对于这部分的测试,我想结果是毫无因为,那么你应该关注什么呢?没错,SQL,所以,我们直接看SQL。当然,结果也是可以看到的。

==>  Preparing: SELECT id,name,age,info,is_delete,create_time,update_time,gender,idcard_id,city_id FROM t_student WHERE name = ? AND age = ? 
==> Parameters: 西夏(String), 26(Integer)
<==    Columns: id, name, age, info, is_delete, create_time, update_time, gender, idcard_id, city_id
<==        Row: 1035789714459471874, 西夏, 26, <<BLOB>>, 0, 2018-09-01 15:21:26.0, 2018-09-01 15:21:26.0, 1, 1035789714388168706, 1035762001753501698
<==      Total: 1

我们还可以这样写:

QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
queryWrapper.lambda()
        .and(obj ->
                obj.eq(Student::getName, "西夏")
                    .eq(Student::getAge, 26));

List<Student> studentList = list(queryWrapper);
for (Student student : studentList)
    Console.info(new Gson().toJson(student));

【2】or

第一种:

QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
queryWrapper.lambda()
        .or(obj1 -> obj1.eq(Student::getName, "西夏"))
        .or(obj2 -> obj2.eq(Student::getName, "1"));
List<Student> studentList = list(queryWrapper);
for (Student student : studentList)
    Console.info(new Gson().toJson(student));

sql:

SELECT * FROM t_student WHERE ( name = ? ) OR ( name = ? ) 

第二种:

QueryWrapper<Student> queryWrapper = new QueryWrapper<>();
queryWrapper.lambda()
        .eq(Student::getName, "西夏")
        .or()
        .eq(Student::getName, "1");
List<Student> studentList = list(queryWrapper);
for (Student student : studentList)
    Console.info(new Gson().toJson(student));

SQL:

SELECT * FROM t_student WHERE name = ? OR name = ? 

这样的话,我们就可以拼接各种条件了。那么问题来了:到底有哪些关键字呢?性能如何呢?

条件构造器

条件参数说明

查询方式说明
setSqlSelect设置 SELECT 查询字段
whereWHERE 语句,拼接 + WHERE 条件
andAND 语句,拼接 + AND 字段=值
andNewAND 语句,拼接 + AND (字段=值)
orOR 语句,拼接 + OR 字段=值
orNewOR 语句,拼接 + OR (字段=值)
eq等于=
allEq基于 map 内容等于=
ne不等于<>
gt大于>
ge大于等于>=
lt小于<
le小于等于<=
like模糊查询 LIKE
notLike模糊查询 NOT LIKE
inIN 查询
notInNOT IN 查询
isNullNULL 值查询
isNotNullIS NOT NULL
groupBy分组 GROUP BY
havingHAVING 关键词
orderBy排序 ORDER BY
orderAscASC 排序 ORDER BY
orderDescDESC 排序 ORDER BY
existsEXISTS 条件语句
notExistsNOT EXISTS 条件语句
betweenBETWEEN 条件语句
notBetweenNOT BETWEEN 条件语句
addFilter自由拼接 SQL
last拼接在最后,例如:last("LIMIT 1")

注意! xxNew 都是另起 ( ... ) 括号包裹。

自定义sql

如果官方提供的满足不了你的需求,或者你的需求很复杂,导致你不知道如何使用条件构造器,那应该怎么办呢?

很简单。

第一步:找到 Dao,写一个数据库操作接口

public interface StudentDao extends BaseMapper<Student> {
    
    List<Student> selectAll();
    
}

第二步:在xml文件中写sql

<!--List<Student> selectAll();-->
<select id="selectAll" resultMap="BaseResultMap">
    select * from t_student
</select>

这样我们就可以使用了:

@Resource
StudentDao studentDao;

List<Student> studentList = studentDao.selectAll();
for (Student student : studentList){
    Console.info(new Gson().toJson(student));
}

测试:

èªå®ä¹sqlæµè¯

封装我们自己的Service

前面我们就说了,我是很不喜欢MP的查询接口的,我们就把他弄成我们喜欢的吧,我这里借鉴 JPA接口了,哈哈

interface:

/**
 * 查询所有数据
 * @return List<Student>
 */
List<Student> findAll();

/**
 * 查询部分数据
 * @return List<Student>
 */
List<Student> findList();

/**
 * 查询一条数据
 * @return Student
 */
Student findOne();

/**
 * 根据主键ID查询数据
 * @param id 主键ID,为null,返回null
 * @return Student
 */
Student findById(Long id);

impl:

@Override
public List<Student> findAll() {
    return list(null);
}

@Override
public List<Student> findList() {
    return list(null);
}

@Override
public Student findOne() {
    return getOne(null);
}

@Override
public Student findById(Long id) {
    ExceptionUtil.notNull(id, "id must not null.");
    return getById(id);
}

来试一下:

å°è£serviceæ¥å£

 

参考: 

资料

[1] MyBatis-Plus测试示例

[2] 官网测试例子:WrapperTest.java

  • 9
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
mybatis-plus-generator和mybatis-plus是用于简化MyBatis开发的两个工具。mybatis-plus是一个MyBatis的增强工具包,提供了一些便捷的操作,节约了编写简单SQL的时间。而mybatis-plus-generator是一个代码生成器,可以自动生成一些基本的Controller、Service、Mapper和Mapper.xml文件。 通过整合mybatis-plusmybatis-plus-generator,我们可以更高效地开发项目中的单表增删改查功能。使用mybatis-plus-generator可以自动生成一些基本的文件,例如Controller、Service、Mapper和Mapper.xml,极大地减少了手动创建这些文件的时间和工作量。而mybatis-plus提供的便捷操作可以节约编写简单SQL的时间。 然而,对于一些逻辑复杂、多表操作或动态SQL等情况,建议使用原生SQL来处理。mybatis-plus支持原生SQL的使用,通过写原生SQL可以更灵活地满足这些复杂需求。 综上所述,通过整合mybatis-plusmybatis-plus-generator,我们可以在开发中更高效地处理单表的增删改查功能,并且对于复杂的需求可以使用原生SQL来满足。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [Spring cloud整合MyBatis-plusmybatis-plus-generator](https://blog.csdn.net/cssweb_sh/article/details/123767029)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *3* [mybatis-plus-generator(mybatisplus代码生成器篇)](https://blog.csdn.net/b13001216978/article/details/121690960)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值