栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Mybatis Plus中插入数据后如何获取新数据的id值

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Mybatis Plus中插入数据后如何获取新数据的id值

问题描述:

Mybatis Plus的insert方法,按说插入数据后会自动返回id
mapper方法:

@DS("wxuser")
@Mapper
public interface UserInfoMapper extends BaseMapper {

}

业务类:

		@Autowired
		UserInfoMapper userInfoMapper;

		UserInfo user = new UserInfo();
        user.setAddress(userInfo.getAddress());
        user.setAge(userInfo.getAge());
        user.setMobile(userInfo.getMobile());
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        // 此num是指的插入数据成功的条数
        int num = userInfoMapper.insert(user);
        //如果想要获取插入数据的id,需要:user.getUserId();
        int id = user.getUserId();

这样按说是可以的,但是我这里仍然获取不到,所以需要再修改。

解决方法:

修改后mapper类:

@DS("wxuser")
@Mapper
public interface UserInfoMapper extends BaseMapper {

    int saveUserInfo(@Param("userInfo")UserInfo userInfo);

}

在resources目录中新建mapper目录,创建UserInfoMapper.xml文件:
注意三个值:
useGeneratedKeys=“true”
说明:允许 JDBC 支持自动生成主键,需要数据库驱动支持。如果设置为 true,将强制使用自动生成主键。尽管一些数据库驱动不支持此特性,但仍可正常工作(如 Derby)。
(仅适用于 insert 和 update)这会令 MyBatis 使用 JDBC 的 getGeneratedKeys 方法来取出由数据库内部生成的主键(比如:像 MySQL 和 SQL Server 这样的关系型数据库管理系统的自动递增字段),默认值:false。

keyProperty=“userInfo.userId”
说明:keyProperty中对应的值是实体类的属性,而不是数据库的字段

keyColumn=“userId”





    
        insert into userInfo (userNick,userName,password,isdelete,address,mobile)  values (#{userInfo.userNick},#{userInfo.userName},#{userInfo.password},#{userInfo.isDelete},#{userInfo.address},#{userInfo.mobile})
    


application.yml文件中:

# Mybatis Plus
mybatis-plus:
  configuration:
    map-underscore-to-camel-case: false # 设置字段不使用下划线方式
  global-config:
    db-config:
      id-type: AUTO
      table-underline: false # 设置表名字不使用下划线方式
  mapper-locations: classpath*:/mapper*.xml

修改后的业务类:

		@Autowired
		UserInfoMapper userInfoMapper;

		UserInfo user = new UserInfo();
        user.setAddress(userInfo.getAddress());
        user.setAge(userInfo.getAge());
        user.setMobile(userInfo.getMobile());
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        // 此num是指的插入数据成功的条数
        int num = userInfoMapper.saveUserInfo(user);
        //如果想要获取插入数据的id,需要:user.getUserId();
        int id = user.getUserId();

这样就可以获取到新插入数据的id值了

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/955926.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号