一、Mybatis參數
Mybatis是一個優秀的持久層框架,在使用過程中,我們難免會使用到各種參數。其中之一就是mybatislist參數。但是,首先需要了解mybatis的參數類型。
mybatis的參數可以分為以下三種:
1、基本類型:如int、double、float等
2、POJO:持久化Java對象
3、Map:鍵值對集合
同時,在mybatis的參數中也可能會出現多個參數,如何解決?
這就需要用到mybatis的Param註解。使用Param註解後,mybatis可以識別多個參數。例如:
public class User{ private int age; private String name; } public interface UserDao{ User getUserByNameAndAge(@Param("name") String name, @Param("age") int age); }
二、Mybatislist為空判斷
當mybatislist參數為空時,我們需要根據情況做出相應的處理:
1、在xml中判斷
使用mybatis的<if>標籤,如下所示:
<select id="getUserList"> select * from user <if test="mybatislist != null and mybatislist.size() > 0"> where id in <foreach collection="mybatislist" item="id" separator=","> #{id,jdbcType=INTEGER} </foreach> </if> </select>
2、在Java代碼中判斷
使用StringUtils.isEmpty()方法即可:
public List<User> getUserList(List<Integer> mybatislist) { if (StringUtils.isEmpty(mybatislist)) { return new ArrayList<>(); } return userDao.getUserList(mybatislist); }
三、Mybatis兩個參數查詢
在mybatis的開發中,我們也會遇到需要兩個參數的查詢。這時需要在xml中使用<select>標籤,並在其中定義參數類型。如下所示:
<select id="getUserByNameAndAge"> select * from user where name=#{name} and age=#{age} </select>
在Java代碼中,相應的方法是這樣的:
public User getUserByNameAndAge(String name,int age){ return userDao.getUserByNameAndAge(name,age); }
四、Mybatislist查詢
mybatislist參數最常用的就是按照id批量查詢數據,這種情況下,我們需要用到foreach標籤,如下所示:
<select id="getUserList"> select * from user where id in <foreach collection="mybatislist" item="id" separator=","> #{id,jdbcType=INTEGER} </foreach> </select>
在Java代碼中,相應的方法是這樣的:
public List<User> getUserList(List<Integer> mybatislist) { return userDao.getUserList(mybatislist); }
五、Mybatis拼接參數
在mybatis中,我們有時需要將參數拼接成字元串。這時需要使用${}來引用參數,如下所示:
<select id="getUserNameById"> select name from user where id=${id} </select>
在Java代碼中,相應的方法是這樣的:
public String getUserNameById(int id) { return userDao.getUserNameById(id); }
六、Mybatis與
在mybatis中,我們可以使用AND關鍵字來連接多個條件,以實現複雜的查詢需求。如下所示:
<select id="getUserByNameAndAge"> select * from user where name=#{name} and age=#{age} </select>
在Java代碼中,相應的方法是這樣的:
public User getUserByNameAndAge(String name,int age){ return userDao.getUserByNameAndAge(name,age); }
七、Mybatis操作資料庫
在使用mybatis操作資料庫時,我們需要注意幾個問題:
1、事務的處理
mybatis的事務處理主要是通過Spring等框架來完成。
2、異常的處理
在進行資料庫操作時,很容易會出現異常。為了避免程序因異常導致運行失敗,我們需要在程序中對異常進行處理。
3、數據源的配置
在mybatis中,我們需要配置數據源。常用的數據源有三種:
1、JDBC數據源
2、C3P0數據源
3、Druid數據源
八、Mybatisplus多表
Mybatisplus是在mybatis基礎上的增強版,提供了許多方便的操作。其可以簡化mybatis多表查詢的開發。實現多表查詢的方式有兩種:
1、使用多個數據源(適用於分表存儲)
2、使用聯表查詢(適用於業務邏輯關聯查詢)
九、Mybatis的in查詢
在mybatis中,我們可以使用in關鍵字來進行多條件查詢。如下所示:
<select id="getUserList"> select * from user where id in <foreach collection="mybatislist" item="id" separator=","> #{id,jdbcType=INTEGER} </foreach> </select>
在Java代碼中,相應的方法是這樣的:
public List<User> getUserList(List<Integer> mybatislist) { return userDao.getUserList(mybatislist); }
十、Mybatis集成Spring
在將mybatis集成到Spring中時,需要進行以下步驟:
1、配置數據源
2、在配置文件中開啟mybatis
3、掃描DAO
4、組裝Mapper
在做好這些準備工作之後,就可以方便地在Spring中使用mybatis了。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/290840.html