Home > Database > Mysql Tutorial > MyBatis+MySQL 返回插入记录的主键ID_MySQL

MyBatis+MySQL 返回插入记录的主键ID_MySQL

WBOY
Release: 2016-06-01 13:07:48
Original
843 people have browsed it

今天用到了多个表之间的关系,另一个表中的一个字段要以第一个表的主键作为外键。

下面说两种方法,MyBatis+MySQL 返回插入记录的主键ID:

第一种:

<insert id="insertAndGetId" usegeneratedkeys="true" keyproperty="userId" parametertype="com.chenzhou.mybatis.User">	insert into user(userName,password,comment)	values(#{userName},#{password},#{comment})</insert>
Copy after login

第二种:

<insert id="insert" parametertype="cn.***.beans.LogObject">	<selectkey resulttype="java.lang.Integer" order="BEFORE" keyproperty="id">		SELECT LOGS_SEQ.nextval AS ID FROM DUAL	</selectkey>	INSERT INTO S_T_LOGS (		ID, 		USER_ID, 		USER_NAME, 		USER_IP, 		OPERATION_TIME, 		DESCRIPTION, 		RESOURCE_ID) 	VALUES (		#{id}, 		#{userId}, 		#{userName}, 		#{userIp}, 		#{operationTime}, 		#{description}, 		#{resourceId})</insert>
Copy after login


这两种写法都可以,但有两点一定要注意:

一: keyProperty="id" 这个id必须是实体的id,而不是数据表的主键id,否则,得不到正确的返回结果;

二:接收返回值时候,必须用实体的get属性,而不能定义变量,否则,接收不到正确的返回结果:即必须用user.getId()来接收。


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template