提示:有不清楚的可以試着看一下我最后的連接,是跟這些內容相關的
Mapper文件,特殊符號:
轉義符號 | 原符號 | 中文意思 |
---|---|---|
&It; | < | 小於號 |
> | > | 大於號 |
& | & | 和 |
' | ' | 單引號 |
" | " | 雙引號 |
在Mapper xml文件寫一些符號,有時候識別不了,就會出錯,就需要用到上面的轉義字符了。
或者為了方便用<![CDATA[]]>也是可以的,在下面的例子代碼也有用到。
例如:
1 col_name <![CDATA[ >= ]]> #{colVal} 【例1】 2 3 <![CDATA[ and w.WORK_DAY <= #{workdayEnd} ]]> 【例2】
Mapperxml文件的參數說明:
resultMap:resultMap是Mybatis最強大的元素,它可以將查詢到的復雜數據(比如好幾個表結合起來的數據)映射到【某個類型】的集當中。
例如:我已經寫好了需要的pojo類【workRecordBo】,里面有我需要用的字段。
寫類字段需要注意:
mybatis默認是屬性名和數據庫字段名一一對應的,即
數據庫表列:user_name
實體類屬性:user_name
但是java中一般使用駝峰命名
數據庫表列:user_name
實體類屬性:userName
我在xml中需要這樣寫:property="類里面的字段名" ,column="數據庫里面對應的字段"
1 <resultMap id="workRecordBo" type="com.ribao.entity.bo.WorkRecordBo" > 2 <result property="workDay" column="WORK_DAY"/> 3 </resultMap>
id:與繼承BaseMapper的接口中的方法名一樣
例如:我的接口是這樣的 public interface WorkRecordMapper extends BaseMapper<WorkRecord>{}
我的方法名: public void getWorkRecord(@Param("workdayStart")String workdayStart,@Param("workdayEnd")String workdayEnd,@Param("teamid")String teamid);
@Param()是與xml文件中的#{}綁定在一起的,名字一定要相同,數據類型也要相同。
例如:@Param("workdayStart")對應xml文件的 #{workdayStart}
resultType:resultType是sql映射文件中定義返回值類型,返回值有基本類型,對象類型,List類型,Map類型等,這里目前只說【對象類型】。
對象類型:寫全類名
例如:java文件中
package com.ribao.entity.bo; public class WorkRecordBo {......}
我的類名就是:resultType="com.ribao.entity.bo.WorkRecordBo"
Mapper的xml文件寫select語句+where條件篩選:
1 <select id="selectWorkRecord" resultType="com.ribao.entity.bo.WorkRecordBo" resultMap="workRecordBo"> 2 SELECT e.EMPLOYEE_ID,t.TEAM_NAME,p.PROJECT_NAME,b.BIG_NAME,s.SMALL_NAME,l.LAN_NAME,WORK_DA,w.REMARK 3 from WORKRECORD w 4 join PROJECT p on p.PROJECT_ID=w.PROJECT_ID 5 join BIGCATEGORY b on b.BIG_ID=w.BIG_ID 6 join SMALLCATEGORY s on s.SMALL_ID=w.SMALL_ID 7 join EMPLOYEE e on e.EMPLOYEE_ID=w.EMPLOYEE_ID 8 join TEAM t on t.TEAM_ID=w.TEAM_ID 9 join LANGUAGE l on l.LAN_NO=w.LAN_NO 10 11 <where> 12 <if test="workdayStart != null and workdayStart !='' " >//workdayStart為非空的時候執行 13 w.WORK_DAY >= #{workdayStart} 14 </if> 15 16 <if test="workdayEnd != null and workdayEnd !='' " > 17 <![CDATA[ and w.WORK_DAY <= #{workdayEnd} ]]> 18 </if> 19 20 <if test="teamidList != null and teamidList !='' " > 21 and w.TEAM_ID in 22 <foreach collection="teamidList" index="index" item="teamid" open="(" separator="," close=")"> 23 #{teamid} 24 </foreach> 25 </if> 26 27 </where>
可參考的博客:
【Java】數據庫mapper與實體字段對應,SpringBoot開啟駝峰映射 網址:https://blog.csdn.net/hr952909686/article/details/91344655
Mybatis:resultMap的使用總結網址:https://www.cnblogs.com/kenhome/p/7764398.html
學習 mybatis的官方網址:https://mybatis.org/mybatis-3/zh/sqlmap-xml.html