主鍵回填的幾種方式

主鍵回填的幾種方式

JDBC原生寫法

Connection con = null;
PreparedStatement pa = null;
ResultSet rs = null;

con = JDBCUtils.getConnection();

ps = con.prepareStatement("INSERT INTO person(username,password) VALUES(?,?)", PreparedStatement.RETURN_GENERATED_KEYS);

ps.setObject(1,person.getUsername());
ps.setObject(2,person.getPassword());
int i = ps.executeUpdate();

rs = ps.getGeneratedKeys();
int id = -1;
if(rs.next()){
	id = rs.getInt(1);
}

// 主鍵
System.out.println(id);
解析:

一、在構造 PreparedStatement 時加上PreparedStatement.RETURN_GENERATED_KEYS,指定需要主鍵回填。

二 、執行更新操作後,調用getGeneratedKeys(),返回一個結果集,從這個遊標集可以獲取到剛剛插入主鍵id。

mybatis寫法

方式一:

在insert語句上,添加useGeneratedKeys=“true” keyProperty=“id”

<mapper namespace="com.mapper.UserMapper">
    <insert id="insert" useGeneratedKeys="true" keyProperty="id" parameterType="com.domain.User">
        insert into t_user VALUES (#{id},#{username},#{sex},#{birthday},#{address})
    </insert>
</mapper>
方式二:

利用MySQL自帶的 last_insert_id() 函數查詢剛剛插入的id

<insert id="insert" parameterType="com.domain.User">
    <!--通過mybatis框架提供的selectKey標籤獲得自增產生的ID值-->
    <selectKey resultType="Integer" order="AFTER" keyProperty="id">
        select LAST_INSERT_ID()
    </selectKey>

    insert into t_user VALUES (#{id},#{username},#{sex},#{birthday},#{address})
</insert>
結果爲:

在這裏插入圖片描述

總結:

主鍵回顯常用的有三種方式,這裏推薦mybatis的兩種方式。

主鍵回填

利用主鍵回填來獲得主鍵值以便於以後的關聯其他功能。

JDBC中的Statement對象在執行插入SQL後,可以通過getGenetatedKeys方法來獲得數據庫生成的主鍵。在insert語句中有一個開關屬性useGeneratedKeys,用來控制是否打開這一個功能,它的默認值是false。當打開了這一個開關,還要配置其屬性keyProperty,告訴系統把主鍵的值放在哪一個屬性中,如果存在多個主鍵,可以用","來隔開。

  1. <!--包含主鍵回填功能-->
  2. <insert id="insertRole" parameterType="role" useGeneratedKeys="true" keyProperty="id">
  3. insert into t_role(role_name,note) values(#{roleName},#{note})
  4. </insert>

則主鍵的ID會對應賦值給這一個role 的POJO對象。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章