MyBatis框架:第四章:插入記錄并返回主鍵

往數(shù)據(jù)庫插入數(shù)據(jù)后,返回數(shù)據(jù)主鍵信息。有兩種方法。
一種:使用insert標(biāo)簽中的useGeneratedKeys屬性和keyProperty屬性組合使用獲取主鍵信息。
一種:使用子元素selectKey標(biāo)簽執(zhí)行sql語句獲取。

<!-- 插入用戶
	useGeneratedKeys="true"
	表示返回生成的主鍵
	keyProperty 表示把返回的key注入到返回值的哪個屬性中
	keyProperty="id" 表示把返回的id主鍵值注入到返回對象的id屬性中
 -->
<insert id="saveUser" useGeneratedKeys="true" keyProperty="id" 
	parameterType="com.pojo.User">
	insert into t_user(last_name,sex) values(#{lastName},#{sex})
</insert>

標(biāo)簽的使用
selectKey 通過前置或后置操作,返回數(shù)據(jù)的主鍵值。
插入記錄并返回主鍵主要是在標(biāo)簽中添加一個

的作用主要就是為了返回插入記錄后,自動生成的主鍵信息
order 表示執(zhí)行的順序。
AFTER 表示在插入之后執(zhí)行。
BEFORE 在插入之前執(zhí)行。
keyProperty 屬性設(shè)置對象的哪個屬性接收
resultType 屬性設(shè)置返回值類型。

<!-- 插入用戶 -->
<insert id="saveUser" parameterType="com.pojo.User">
	<!-- 
		selectKey標(biāo)簽主要用于插入數(shù)據(jù)后,獲取生成的主鍵。
		order 表示執(zhí)行的順序,AFTER表示在插入之后執(zhí)行。BEFORE在插入之前執(zhí)行。
		keyProperty屬性設(shè)置對象的哪個屬性接收
		resultType屬性設(shè)置返回值類型。
	 -->
	<selectKey order="AFTER" keyProperty="id" resultType="int">
		SELECT LAST_INSERT_ID()
	</selectKey>
	insert into t_user(last_name,sex) values(#{lastName},#{sex})
</insert>

selectKey 返回Oracle的序列自增主鍵

<selectKey order="BEFORE" resultType="int" keyProperty="id"> 
     select 序列名.nextval as id from dual 
</selectKey>