SSM框架——Mybatis的select標籤不同參數詳解

< select>元素的常用屬性:

屬性 說明
id 命名空間中唯一的標識符
parameterType 傳入sql語句的參數類的全限定名或別名(可選)
resultType 從SQL語句中返回的類型的類的全限定名或別名。 若是集合類型,則返回的應是集合可包含的類型, 而不是其本身。
resultMap 外部resultMap的命名引用。返回時可用resultType或resultMap
flushCache 調用SQL語句後,是否需要Mybatis清空之前查詢的本地緩存和二級緩存。(默認:false)
useCache 控制二級緩存的開啓和關閉(默認:true)
timeout 設置超時參數,單位:秒
fetchSize 獲取記錄的總條數設定
statementType 設置Mybatis使用哪個jdbc的statement工作,其值爲STATEMENT、PREPARED(默認)或CALLABLE
resultSetType 結果集的類型
一、單個參數
public Book findBookById(String bookId);
<select id="findBookById" parameterType="String" resultMap="bookDetail">
        select *
        from l_book
        where book_id = #{bookId}
</select>
    <resultMap id="bookDetail" type="po.Book" >
        <id property="bookId" column="book_id"/>
        <result property="isbn" column="book_isbn" />
        <result property="bookPlace" column="book_place"/>
        <result property="publishDate" column="book_date"/>
        <result property="bookName" column="book_name" />
        <result property="author" column="book_author" />
        <result property="publisher" column="book_publisher" />
        <result property="bookPage" column="book_page"/>
        <result property="price" column="book_price"/>
    </resultMap>
  • id:命名空間中唯一的標識符
  • select 的 id 要和方法名稱一致
  • 參數名稱也要一致
  • 這裏因爲數據庫字段名稱和bean的字段名稱不一樣,所以使用了resultMap,注意名稱要和< select> 中 的resultMap一致
    不需要映射的直接寫 resultMap = "Book"即可
二、多個參數
public List<Book> findBookByfield(String field, String info);
 <select id="findBookByfield" resultMap="bookDetail">
        select *
        from l_book
        where ${arg0} like concat('%', #{arg1}, '%')
    </select>
  • 注意${} 和 #{}的區別:
    ${ } 的變量的替換階段是在動態 SQL 解析階段,而 #{ }的變量的替換是在 DBMS 中;
    #{}將傳入的參數當成一個字符串,會給傳入的參數加一個雙引號;
    ${}不會添加引號,一般用於傳輸數據庫的表名、字段名等,無法防止sql注入問題
  • 第一個參數用#{arg0}或者$ {arg0}獲取,第二個爲#{arg1}或$ {arg1}
  • 不能使用parameterType
三、Map封裝多參數
public List<Book> findBookByPageNum(Page page);
<select id="findBookByPageNum" parameterType="po.Page" resultMap="bookDetail">
        select *
        from l_book
        limit #{startRecord}, #{endRecord}
</select>
  • startRecord和endRecord是Page中的字段名,有getter方法
四、< foreach>元素(循環遍歷可迭代參數)

< foreach>元素常用於構建IN條件語句

public List<Book> findBookByList(List list);
<select id="findBookByList" parameterType="List" resultMap="bookDetail">
    select * from l_book where book_id in 
	<foreach collection="list" item="id" index="index" open="(" separator="," close=")">
		#{id}
	</foreach>
</select>
  • item:循環中的當前元素
  • index:當前元素在集合的下標
  • collection:list傳遞過來的參數類型(首字母小寫),可以是array、list或collection、Map集合的鍵、POJO包裝類中的數組或集合類型的屬性名等。
    注意:1、collection爲可迭代對象或數組時,index:當前迭代的次數,item:本次迭代獲取的元素
        2、collection爲字典或Map.Entry對象的集合時,index是鍵,item是值
  • open和close:將這些集合元素包裝起來的符號
  • separator:各個元素之間的間隔符

在控制檯輸出mysql語句
    <!--在控制檯輸出sql語句-->
<settings>
	<setting name="mapUnderscoreToCamelCase" value="true" />
	<setting name="logImpl" value="STDOUT_LOGGING" />
</settings>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章