mybatis配置获取自增主键
01 使用场景
- 当需要刚刚插入数据库的数据对应的新增主键时,通过配置xml文件,使数据库返回新增主键id,并把主键id与类参数对应
02 涉及配置
- 注解@tableid(type = idtype.auto):在类主键id通过配置实现插入数据库时主键自增
public class xzsquestionsanswercreate { @apimodelproperty(value = "选项内容",required = true) @notblank(message = "选项内容不能为空") private string xzsoptiontext; @apimodelproperty(value ="选项标题",required = true) @notblank(message = "选项标题不能为空") private string xzsoptiontitle; @tableid(type = idtype.auto) @apimodelproperty("标准答案id") private long answerid; }
- mapper(数据操作层):正常插入接口
int savequestionanswer(@param("questionid")long questionid, @param("list")list<xzsquestionsanswercreate> xzsquestionsanswercreate);
- 关键部分:配置mysql插入数据对应的返回值
<insert id="savequestionanswer" usegeneratedkeys="true" keyproperty="list.answerid" keycolumn="xzs_question_options_id"> insert into xzs_question_options ( xzs_question_id, xzs_option_text, xzs_option_title ) values <foreach collection="list" item="option" open="(" separator="), (" close=")"> #{questionid},#{option.xzsoptiontext}, #{option.xzsoptiontitle} </foreach> </insert>
03 关键部分使用
字段 | 作用 |
---|---|
usegeneratedkeyss=“true” | 开启主键自增返回设置 |
keyproperty | 类属性 |
keycolumn | 数据库字段 |
- keyproperty对应的是返回的自增主键对应的属性,list中answerid属性会在插入语句后被赋值
- mapper层函数中的返回值int,依旧是插入改变了多少行语句,不是自增主键
int savequestionanswer(@param("questionid")long questionid, @param("list")list<xzsquestionsanswercreate> xzsquestionsanswercreate);
keycolumn对应的是数据库中的字段
到此这篇关于mybatis配置获取自增主键的操作方法的文章就介绍到这了,更多相关mybatis获取自增主键内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论