MyBatis的動態(tài)SQL語句實現(xiàn)
1. 動態(tài)SQL之<if>標簽
我們根據(jù)實體類的不同取值,使用不同的SQL語句來進行查詢。比如在id如果不為空時可以根據(jù)id查詢,如果username不為空時還要加入用戶名作為條件,這種情況在我們的多條件組合查詢中經(jīng)常會碰到。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.joker.dao.IUserDao">
<select id="findByUser" resultType="user" parameterType="user">
select * from user where 1=1
<if test="username!=null and username != '' ">
and username like #{username}
</if>
<if test="address != null">
and address like #{address}
</if>
</select>
</mapper>
注意:<if>標簽的test屬性中寫的是對象的屬性名,如果是包裝類的對象要使用OGNL表達式的寫法。另外要注意where 1=1的作用。
2. 動態(tài)SQL之<where>標簽
為了簡化上面where 1=1的條件拼裝,我們可以采用<where>標簽來簡化開發(fā)。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.joker.dao.IUserDao">
<select id="findByUser" resultType="user" parameterType="user">
select * from user
<where>
<if test="username!=null and username != '' ">
and username like #{username}
</if>
<if test="address != null">
and address like #{address}
</if>
</where>
</select>
</mapper>
3. 動態(tài)SQL之<foreach>標簽
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.joker.dao.IUserDao">
<!-- 查詢所有用戶在 id的集合之中
foreach標簽:用于遍歷集合
* collection:代表要遍歷的集合元素,注意編寫時不要寫 #{}
* open:代表語句的開始部分
* close:代表結(jié)束部分
* item:代表遍歷集合的每個元素,生成的變量名
* sperator:代表分隔符
-->
<select id="findInIds" resultType="user" parameterType="queryvo">
select * from user
<where>
<if test="ids != null and ids.size() > 0">
<foreach collection="ids" open="id in ( " close=")" item="uid" separator=",">
#{uid}
</foreach>
</if>
</where>
</select>
</mapper>
4. MyBatis中的SQL片段
MyBatis的sql中可將重復(fù)的sql提取出來,使用時用include引用即可,最終達到sql重用的目的。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.joker.dao.IUserDao">
<!-- 抽取重復(fù)的語句代碼片段 -->
<sql id="defaultSql">
select * from user
</sql>
<select id="findAll" resultType="user">
<include refid="defaultSql"></include>
</select>
<select id="findById" resultType="User" parameterType="int">
<include refid="defaultSql"></include>
where id = #{uid}
</select>
</mapper>
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
使用Eclipse創(chuàng)建Maven的Java WEB項目的兩種方式
本文詳細介紹了如何在JDK 1.8、Maven 3.6.3和Eclipse 2017版本下創(chuàng)建Java Web項目,包括選擇archetype方式、配置Tomcat、設(shè)置為Web3.1、配置Maven編譯級別、修復(fù)Eclipse提示的錯誤、設(shè)置Maven源文件夾等步驟,需要的朋友可以參考下2024-11-11
MybatisPlus實現(xiàn)真正批量插入的詳細步驟
在數(shù)據(jù)庫操作中,批量插入是提升效率的重要手段,MyBatis-Plus提供了多種批量插入方法,但默認的saveBatch方法效率并不高,文章介紹了通過手動拼接SQL、使用IService接口以及自定義insertBatchSomeColumn方法進行優(yōu)化,以實現(xiàn)更高效的批量插入,并給出了性能優(yōu)化建議2024-10-10

