欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

mybatis mapper.xml獲取insert后的自增ID問題

 更新時(shí)間:2024年05月18日 10:35:18   作者:JaneYork  
這篇文章主要介紹了mybatis mapper.xml獲取insert后的自增ID問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

mybatis mapper.xml獲取insert后的自增ID

在MyBatis中,要獲取執(zhí)行INSERT操作后的自增ID,可以在mapper.xml文件中的對應(yīng)<insert>標(biāo)簽中使用useGeneratedKeys屬性和keyProperty屬性。

以下是一個(gè)示例:

<insert id="insertUser" useGeneratedKeys="true" keyProperty="id">
  INSERT INTO users (username, email) VALUES (#{username}, #{email})
</insert>

在這個(gè)例子中,假設(shè)users表有一個(gè)自增主鍵字段id。useGeneratedKeys設(shè)置為true表示我們希望獲取數(shù)據(jù)庫生成的鍵值,keyProperty設(shè)置為Java對象中的屬性名,MyBatis會將生成的ID設(shè)置到這個(gè)屬性中。

確保你的數(shù)據(jù)表設(shè)置了自增主鍵,并且你的實(shí)體類中有對應(yīng)的屬性。

例如:

public class User {
  private Integer id;
  private String username;
  private String email;
 
  // getters and setters
}

在執(zhí)行insertUser操作后,MyBatis會將生成的ID自動設(shè)置到傳入的User對象的id屬性中。

mybatis mapper.xml常用寫法

resultMap寫法

<resultMap id="BaseResultVoMap" type="*.*.*.Entity" >
    <id column="id" property="id" jdbcType="VARCHAR" />
    <result column="value" property="value" jdbcType="VARCHAR" />
    <result column="date" property="date" jdbcType="DATE" />
    <result column="time" property="time" jdbcType="TIMESTAMP" />
    <result column="status" property="status" jdbcType="INTEGER" />
    <result column="bool" property="bool" jdbcType="BOOLEAN" />
</resultMap>

if 書寫

<if test=' value != null and value!= ""'>
     value = #{value}
</if>

foreach 書寫

<foreach collection="ids" item="item" open="(" separator=" , " close=")" index="index">
     #{item}
</foreach>

批量插入 

<insert id="insert" parameterType="java.util.Map">
    insert into table(id, value, date, time, status)
    values
    <foreach collection="list" item="entity" separator=",">
        (
        #{entity.id}, 
        #{entity.value},
        #{entity.date},
        #{entity.time},
        #{entity.status}
        )
    </foreach>
</insert>

批量更新 

<update id="batchUpdate" parameterType="java.util.List">
    <foreach collection="lists" item="item" index="index" open="" close="" separator=";">
        UPDATE table_name
        <set>
            create_time = #{item.createTime}
        </set>
        WHERE id = #{item.id}
    </foreach>
</update>

choose 書寫

<choose>
    <when test=' time != null and time == "1" '>
         table_${time}
    </when>
    <otherwise>
         table_${date}
    </otherwise>
</choose>

大于小于

&lt;=<=
&gt;=>=

sql 書寫

<sql id="BaseColumn">
    id, value, date, time, status
</sql>
 
<select id="selectByPidsAndQids" parameterType="java.util.Map" resultMap="BaseResultVoMap">
    SELECT <include refid="BaseColumn"/>
    FROM table
</select>

resultType中接受Date數(shù)據(jù)類型

<select id="queryMaxDate" resultType="java.util.Date">
      SELECT MAX(date)  as maxDate from dual
</select>

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論