目录
- 1. `MyBatis` 插入数据后返回主键 `id`
- 1.1. `MySQL` 数据库
- 1.1.1. `user` 实体类
- 1.1.2. `Dao` 层接口
- 1.1.3. 测试
- 1.2. `Oracle` 数据库
1. MyBatis
插入数据后返回主键 id
很多时候,在向数据库插入数据时,需要保留插入数据的 id
,以便进行后续的 update
操作或者将 id
存入其他表作为外键。但在默认情况下,insert
操作返回的是一个 int
值,并不是表示主键 id
,而是表示当前 SQL
语句影响的行数
接下来,我们看看 MyBatis
如何在使用 MySQL
和 Oracle
做 insert
插入操作时将返回的 id
绑定到对象中
1.1. MySQL
数据库
<insert id="insertAndGetId" useGeneratedKeys="true" keyProperty="userId" parameterType="com.chenzhou.mybatis.User">
insert into user(userName,password,comment)
values(#{userName},#{password},#{comment})
</insert>
keyProperty
:表示返回的id
要保存到对象的哪个属性中,仅适用于insert
和update
语句useGeneratedKeys
:表示主键id
为自增长模式,默认是false
,仅适用于insert
和update
语句
1.1.1. user
实体类
public class User {
private int userId;
private String userName;
private String password;
private String comment;
// setter and getter
}
1.1.2. Dao
层接口
public interface UserDao {
public int insertAndGetId(User user);
}
1.1.3. 测试
User user = new User();
user.setUserName("chenzhou");
user.setPassword("xxxx");
user.setComment("测试插入数据返回主键功能");
System.out.println("插入前主键为:"+user.getUserId());
userDao.insertAndGetId(user);//插入操作
System.out.println("插入后主键为:"+user.getUserId());
插入前主键为:0
插入后主键为:15
1.2. Oracle
数据库
<insert id="insert" parameterType="com.test.User">
<selectKey resultType="INTEGER" order="BEFORE" keyProperty="userId">
SELECT SEQ_USER.NEXTVAL as userId from DUAL
</selectKey>
insert into user (user_id, user_name, modified, state)
values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{modified,jdbcType=TIMESTAMP}, #{state,jdbcType=INTEGER})
</insert>
Oracle
用法中,需要注意的是:由于 Oracle
没有自增长一说法,只有序列这种模仿自增的形式,所以不能再使用 useGeneratedKeys
属性,而是使用 <selectKey>
将 id
获取并赋值到对象的属性中,insert
插入操作时正常插入 id
更多推荐
MyBatis插入数据后返回主键id
发布评论