MyBatis-Plus | 最簡單的查詢操做教程(Lambda)

引言

上一篇:MyBatis-Plus | 最優雅最簡潔地完成數據庫操做前端

是對MyBatis-Plus的功能進行簡單介紹,雖然是介紹,也讓咱們領略到他的優雅與強大。你是否是已經被吸引了?彆着急,上一節,咱們算是參觀了MyBatis的風景,這一節,我將帶你領略他獨特的魅力。java

Lambda

官方表示,3.x支持Lambda表達式,那應該怎麼使用呢?咱們來看個例子:git

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

看一下測試結果(爲了看好,咱們轉成json):github

{
    "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
}

若是你使用了個人配置,你也能看到相應的SQLsql

==>  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 中配置json

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

第二步:寫分頁代碼(爲了你可以看得清楚,我截圖給你):mybatis

分頁代碼

看結果(json):app

{
    "records":[
        {
            "id":1035788325322752001,
            "name":"1",
            "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 查詢字段
where WHERE 語句,拼接 + WHERE 條件
and AND 語句,拼接 + AND 字段=值
andNew AND 語句,拼接 + AND (字段=值)
or OR 語句,拼接 + OR 字段=值
orNew OR 語句,拼接 + OR (字段=值)
eq 等於=
allEq 基於 map 內容等於=
ne 不等於<>
gt 大於>
ge 大於等於>=
lt 小於<
le 小於等於<=
like 模糊查詢 LIKE
notLike 模糊查詢 NOT LIKE
in IN 查詢
notIn NOT IN 查詢
isNull NULL 值查詢
isNotNull IS NOT NULL
groupBy 分組 GROUP BY
having HAVING 關鍵詞
orderBy 排序 ORDER BY
orderAsc ASC 排序 ORDER BY
orderDesc DESC 排序 ORDER BY
exists EXISTS 條件語句
notExists NOT EXISTS 條件語句
between BETWEEN 條件語句
notBetween NOT 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

相關文章
相關標籤/搜索