MyBatis動態SQL之增 刪 改 查操作

2021-08-11 07:23:23 字數 2236 閱讀 1672

概述

select * from students;

-- 不去限制姓名和年齡

當我們將年齡選擇為》20時,相當於下面的sql語句:

select * from students where age>20;
當我們同時選擇條件姓名為:張三,年齡》20,則相當於下面的sql語句:

select * from students where age>20

and name='張三';

當我們有很多的條件時,此時就需要我們去組合這些條件,並動態的生成乙個可執行的sql語句,這樣就不是乙個簡單的sql語句能夠解決問題,那麼我們該怎麼辦呢?在mybatis中同樣是支援這種動態sql的寫法,具體見下面的內容。

mybatis動態sql支援

動態sql之查詢

<?xml version="1.0" encoding="utf-8"?>

namespace="studentnamespace">

type="com.jpzhutech.entity.student"

id="studentmap">

property="id"

column="id"/>

property="name"

column="name"/>

property="sal"

column="sal"/>

resultmap>

id="findall"

parametertype="map"

resultmap="studentmap">

select id , name , sal

from students

test="pid!=null" >

and id = #

if>

test="pname!=null" >

and name = #

if>

test="psal!=null" >

and sal = #

if>

where>

select>

動態sql之插入

id="key">

suffixoverrides=",">

test="id!=null">

id,if>

test="name!=null">

name,

if>

test="sal!=null">

sal,

if>

trim>

sql>

id="value">

suffixoverrides=",">

test="id!=null">

#,if>

test="name!=null">

#,if>

test="sal!=null">

#,if>

trim>

sql>

id="insertstudent"

parametertype="com.jpzhutech.entity.student">

insert into students(refid="key"/>) values(refid="value"/>);

insert>

動態sql之刪除

id="deletestudent">

delete from students where id in

collection="array"

open="("

close=")"

separator=","

item="ids">

#foreach>

delete>

動態sql之更新

id="updatestudent"

parametertype="map" >

update students

test="pname!=null">

name = #,

if>

test="psal!=null">

sal = #,

if>

set>

where id = #

update>

mybatis學習之動態sql

1 select查詢 簡單的select類似如下 select id findbyid resultmap studentresult parametertype integer select from t student where id select 1 if 常用於各種查詢的條件判斷部分 se...

mybatis動態SQL之if標籤

我們根據實體類的不同取值,使用不同的 sql 語句來進行查詢。比如在 id 如果不為空時可以根據 id 查詢,如果 username 不同空時還要加入使用者名稱作為條件。這種情況在我們的多條件組合查詢中經常會碰到。根據使用者資訊,查詢使用者列表 param user return listfindb...

(七)mybatis學習之動態SQL

mybatis的核心是對sql語句進行靈活的操作,通過表示式進行判斷,對sql進行靈活拼接 組裝。動態sql包括 if choose when,otherwise where set trim foreach sql片段 if標籤比較簡單,這裡記錄一下文件內容的例子,通過看例子,就清楚的知道if是如...