02.TK.Mybatis之Select

TK.Mybatis查詢方法

一、概述

本章節基於第一章節的:01.Mybatis Tk插件環境搭建
TK的內置查詢方法有很多,在該章節主要介紹幾種常用的的方法:

  • selectAll():查詢所有
  • selectByPrimaryKey(Object var1):主鍵查詢
  • selectByExample(Example example):用來複雜查詢

二、單元測試

  • 主鍵查詢
    它會根據主鍵進行查詢,進行傳的是一個對象,它只會拼接主鍵。
	@Test
    public void selectAll(){
        Product param = new Product();
        param.setId(1L);
        param.setProductName("Redis深度歷險記");
        //Product product = productDao.selectByPrimaryKey(1L);  等價下面語句
        Product product = productDao.selectByPrimaryKey(param);
    }
 //==>  Preparing: SELECT id,product_name,price,in_time,out_time FROM product WHERE id = ?
//==> Parameters: 1(Long)
//<==    Columns: id, product_name, price, in_time, out_time
//<==        Row: 1, Redis深度歷險記, 79, 2019-12-21 18:22:20, 2019-12-23 18:22:20
//<==      Total: 1
  • 複雜查詢-1:範圍查詢
    比如:我要查詢入庫時間在:2019-12-19—2019-12-25的商品
@Test
    public void selectBetWeen(){
        Example example = new Example(Product.class);
        
        LocalDateTime from = LocalDateTime.of(2019,12,19,0,0);
        LocalDateTime to = LocalDateTime.of(2019, 12, 26,0,0);

        example.createCriteria().andBetween("inTime", from, to);
        List<Product> products = productDao.selectByExample(example);
    }
    
//==>  Preparing: SELECT id,product_name,price,in_time,out_time FROM //product WHERE ( in_time between ? and ? ) 
//==> Parameters: 2019-12-19 00:00:00.0(Timestamp), 2019-12-26 //00:00:00.0(Timestamp)
//<==    Columns: id, product_name, price, in_time, out_time
//<==        Row: 1, Redis深度歷險記, 79, 2019-12-21 18:22:20, 2019-12-23 //18:22:20
//<==        Row: 2, Java 8 函數編程, 56, 2019-12-24 18:22:20, 2019-12-26 //18:22:20
//<==      Total: 2
  • 複雜查詢-2:多條件查詢 比如:(a or b) and ( c )
    在這裏,我要查詢入庫時間大於等2019-12-25,且出庫時間大於等與2019-12-25的商品。
	@Test
    public void selectByCra(){
        Example example = new Example(Product.class);

        //LocalDateTime cur = LocalDateTime.of(2019,12,25,0,0);
        
        Example.Criteria c = example.createCriteria();
        c.andLessThanOrEqualTo("inTime", "2019-12-25 00:00:00.0");

        Example.Criteria e = example.createCriteria();
        e.andGreaterThanOrEqualTo("outTime", "2019-12-25 00:00:00.0");

        example.and(e);
        List<Product> products = productDao.selectByExample(example);
    }
    
//==>  Preparing: SELECT id,product_name,price,in_time,out_time FROM //product WHERE ( in_time <= ? ) and ( out_time >= ? ) 
//==> Parameters: 2019-12-25T00:00(String), 2019-12-25T00:00(String)
//<==    Columns: id, product_name, price, in_time, out_time
//<==        Row: 2, Java 8 函數編程, 56, 2019-12-24 18:22:20, 2019-12-26 //18:22:20
//<==      Total: 1

觀察上面兩個複雜查詢日誌結果,你會發現一個Criteria 對於一個 ()

三、最後

雖然TK幫助我們省略部分工作,但是隨着查詢條件的複雜度增加,編寫代碼也非常多,感覺不太容易維護。建議:對於複雜條件的sql還是XML方便點,後期維護起來也比較容易。

四、參考

發佈了7 篇原創文章 · 獲贊 2 · 訪問量 750
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章