Mybatis實體類的映射文件中select,insert語句使用


id:在命名空間中唯一的標識符,可以被用來引用這條語句。

parameterType:設置傳入這條語句的參數的數據類型,如int,String......

resultType:設置從這條語句中返回數據的類型。 注意如果返回的是集合,那應該設置為集合包含的類型,而不是集合本身。可以使用

      resultType 或 resultMap,但不能同時使用。

select

1)查詢某個表的所有記錄

<select id="queryall" resultType="com.test.Person">
	select * from person
</select>

 

2)根據某個字段的值查詢

  ① 直接查詢

    傳入的參數值通過 #{id} 傳遞給sql語句(id可自定義為其他的名字)

<!-- 根據id查用戶 -->
<select id="querypersonbyid" parameterType="int" resultType="com.test.Person">
	select * from person where id = #{id}
</select>

  ② 模糊查詢

    原生方法:like "%${value}%"  注意使用的是 $ 並且參數名只能用 value,否則會報錯

<!-- 模糊查詢  -->
<select id="querypersonbyname" parameterType="String" resultType="com.test.Person">
	select * from person where name like "%${value}%"
</select>

    mysql數據庫:like CONCAT('%',#{name},'%')  這里是使用CONCAT進行拼接,name可以為其他名字

<select id="querypersonbyname" parameterType="String" resultType="com.test.Person">
	select * from person where name like CONCAT('%',#{name},'%')
</select>

 

Insert

1)往表中插入一條記錄

<insert id="insertAuthor">
    insert into Author (id,username,password,email,bio)
    values (#{id},#{username},#{password},#{email},#{bio})
</insert>

2)插入時主鍵自動生成

  首先,如果你的數據庫支持自動生成主鍵的字段(比如 MySQL 和 SQL Server),那么你可以設置 useGeneratedKeys=”true”,然后再把 keyProperty 設置到目標屬性上就 OK 了。

<insert id="insertAuthor" useGeneratedKeys="true" keyProperty="id">
    insert into Author (username,password,email,bio)
    values (#{username},#{password},#{email},#{bio})
</insert>

  如果你的數據庫還支持多行插入, 你也可以傳入一個 Author 數組或集合,並返回自動生成的主鍵。

<insert id="insertAuthor" useGeneratedKeys="true" keyProperty="id">
     insert into Author (username, password, email, bio) values
    <foreach item="item" collection="list" separator=",">
        (#{item.username}, #{item.password}, #{item.email}, #{item.bio})
    </foreach>
</insert>

  對於不支持自動生成類型的數據庫或可能不支持自動生成主鍵的 JDBC 驅動,MyBatis 有另外一種方法來生成主鍵。

  selectKey 元素中的語句將會首先運行,person 的 id 會被設置,然后插入語句會被調用。這可以提供給你一個與數據庫中自動生成主鍵類似的行為,同時保持了 Java 代碼的簡潔。

<insert id="insertperson" parameterType="com.test.Person">
    <selectKey keyProperty="id" resultType="int" order="BEFORE">
        select LAST_INSERT_ID()
    </selectKey>
    insert into person(name,age,address,birthday)
    value(#{name},#{age},#{address},#{birthday})
</insert>        

  selectKey 元素描述如下:

<selectKey
  keyProperty="id"
  resultType="int"
  order="BEFORE"
  statementType="PREPARED">

  keyProperty:selectKey 語句結果應該被設置的目標屬性。如果希望得到多個生成的列,也可以是逗號分隔的屬性名稱列表。

  resultType:結果的類型。

  order:這可以被設置為 BEFORE 或 AFTER。如果設置為 BEFORE,那么它會首先生成主鍵,設置 keyProperty 然后執行插入語句。如果設置為AFTER,那么先執行插入語句,然后是 selectKey 中的語句 - 這和 Oracle 數據庫的行為相似,在插入語句內部可能有嵌入索引調用。

  statementType:MyBatis 支持 STATEMENT,PREPARED 和 CALLABLE 語句的映射類型,分別代表 PreparedStatement 和 CallableStatement 類型。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM