Mybatis Plus获取新数据id值

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Mybatis Plus获取新数据id值

葫芦北   2022-09-28 我要评论

问题描述:

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

mapper方法:

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

}

业务类:

		@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<UserInfo> {
    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”

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wx.user.mapper.UserInfoMapper">

    <insert id="saveUserInfo" useGeneratedKeys="true" keyProperty="userInfo.userId" keyColumn="userId">
        insert into userInfo (userNick,userName,password,isdelete,address,mobile)  values (#{userInfo.userNick},#{userInfo.userName},#{userInfo.password},#{userInfo.isDelete},#{userInfo.address},#{userInfo.mobile})
    </insert>

</mapper>

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值了

总结

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们