使用mybatis插入数据(insert)时返回主键的问题

使用mybatis做插入操作时,想要获取新增记录的主键,我发现现在的方式和以前的方式有所区别,即以前是直接通过方法返回,现在是将主键设置在数据实体对象中。

下面对mybatis进行insert时返回主键的问题进行说明。如果有不同意见和想法的朋友可以留言指出。

表结构:

-- Create table
create table USER_INFO
(
  id        VARCHAR2(32),
  login_id  VARCHAR2(50),
  password  VARCHAR2(32),
  user_name VARCHAR2(50),
  status    VARCHAR2(2)
);
-- Add comments to the table 
comment on table USER_INFO
  is '用户信息表';
-- Add comments to the columns 
comment on column USER_INFO.id
  is '主键';
comment on column USER_INFO.login_id
  is '账号';
comment on column USER_INFO.password
  is '密码';
comment on column USER_INFO.user_name
  is '用户名';
comment on column USER_INFO.status
  is '有效状态(0:失效;1:有效)';

Mapper.xml中insert配置

<insert id="insertUserInfo" parameterType="mvc.entity.UserInfo">
        <selectKey keyProperty="id" order="BEFORE" resultType="String">
            select User_Info_sq.nextval as id from dual
        </selectKey>
        insert into user_info(
                                ID,
                                LOGIN_ID,
                                PASSWORD,
                                USER_NAME,
                                STATUS)
                            values(
                                #{id},
                                #{login_id},
                                #{password},
                                #{user_name},
                                #{status}
                            )
    </insert>

id是主键,我创建了序列来给id赋值,值从1开始,每次增加1。如果要返回主键,需要有<selectKey></selectKey>,这样即给insert语句中的id赋值,同时也是返回主键的设置。

DAO中方法为:

public String insertUserInfo(UserInfo userInfo);

这样在插入成功后就能接收到新增记录的主键。

String id=userInfoService.insertUserInfo(ui);

但是最近我使用上面这种方法,在注册的时候就会报错,在查询了很多之后才发现问题,就是现在的插入方法返回值只是插入的记录条数,而主键是在插入数据的实体类对象中。

新代码

DAO中方法为:

public int insertUserInfo(UserInfo userInfo);

Controller中代码:

UserInfo ui=new UserInfo();
ui.setLogin_id(userInfo.getLogin_id());
ui.setUser_name(userInfo.getUser_name());
ui.setPassword(MD5Utils.getMD5_32bits(userInfo.getPassword()));
ui.setStatus("1");
int num=userInfoService.insertUserInfo(ui);

num是插入的记录数,而主键是在ui对象中的,即

String id=ui.getId();

猜你喜欢

转载自www.cnblogs.com/lizs0314/p/9667238.html
今日推荐