mybatis的mapper.xml中sql的用法
阿新 • • 發佈:2018-12-21
剛接觸的時候會有些摸不到頭腦,為此在網上搜索了一些相關的參考給自己作為借鑑
1.根據id查詢
select * from test_tb_info where 1=1 <if test="id != null and id !=''"> and info.id=#{id} </if> <if test="...."> ....... </if> </select> <resultMap type="com.....test.testFileBean" id="testFileBean"> <id column="id" property="id" /> //主鍵與其他欄位有區別,需要注意 <result column="age" property="age"/> //column表示欄位在資料庫中對應的名稱,property表示在實體bean中對應的名稱 <result column="name" property="name" /> <result column="path" property="path" /> </resultMap> parameterType表示給sql語句傳入的引數的型別,如上java.lang.String; resultMap表示返回的型別是一個map集合,如上testFileBean,testFileBean是一個引用型別,表示的是上面id為testFileBean的 resultMap片段。id是作為標記使用,確保sql語句在mapper.xml中的唯一性。 if是用來對其內部欄位id進行判斷,test屬性表示判 斷的條件。
2.根據id刪除檔案
<delete id="delete" parameterType="java.lang.String" >
delete from tb_test where id = #{delId}
</delete>
#{delId}表示的是我們的傳入的id屬性的名稱,必須與實體bean中的命名相同。刪除沒有返回,所以我們只需要寫輸入型別。
- 新增
<insert id="insert" parameterType="TestInfoBean"> isnert into test_info(id,name) values (#{id},#{name}) </insert>
4.修改
<update id="update" parameterType="TestInfoBean"> update test_info set id=#{id},name=#{name} where id=#{id} //和我們寫sql語句一樣,只是把引數值換為#{...}變數 </update> 也可以這樣寫: <update id="update" parameterType="TestInfoBean"> update test_info <set> id=#{id},name=#{name} </set> //使用set標籤 where id=#{id} </update
5.<動態sql片段的使用
<sql id="select_test">
<if test="id != null"> and id=#{id}</if>
<if test="name != null and name.length()>0"> and name=#{name}</if>
<if test="age != null and age.length()>0"> and age=#{age}</if>
</sql>
原作者:zhb_Simple
來源:CSDN
原文:https://blog.csdn.net/zhb_simple/article/details/78678534