mybatis 框架
方法一:
TeamInfo teamInfo = new TeamInfo();
teamInfo.setTeamName(context.getTeamName());
teamInfo.setSource(context.getSource());
teamInfo.setCreateDatetime(new Date());
teamInfo.setUpdateDatetime(new Date());
teamInfo.setDelFlag(CommonConstant.DEL_FLAG_NODEL);
teamInfoMapper.insert(teamInfo);
Long id = teamInfo.getId();
System.out.println("id===" + id);
这样 直接 getId 可以拿到当前的Id
方法二
<insert id="insertDemo" >
INSERT INTO team_info (team_name, `source`, create_datetime, update_datetime, del_flag)
VALUES ('大仙集团', '大仙集团', '2022-06-01 11:32:24', '2022-06-01 11:32:24', '0')
<selectKey keyProperty="id" order="AFTER" resultType="java.lang.Long">
select LAST_INSERT_ID()
</selectKey>
</insert>
在 新增语句中 加入 其中 keyProperty 是 表 中id 在实体类对应的属性;
order 是在 insert 之前执行 还是之后,一般是之后
对应的Java中
TeamInfo teamInfo = new TeamInfo();
Long newId = teamInfoMapper.insertDemo(teamInfo);
System.out.println("newId===" + teamInfo.getId());
必须传入 实体对象,使用 teamInfo.getId() 获取id;
方法三:
<insert id="insertDemo" useGeneratedKeys="true" keyProperty="id">
INSERT INTO team_info (team_name, `source`, create_datetime, update_datetime, del_flag)
VALUES ('大仙集团', '大仙集团', '2022-06-01 11:32:24', '2022-06-01 11:32:24', '0')
</insert>
其中 keyProperty 是 表 中id 在实体类对应的属性;
对应的Java中
TeamInfo teamInfo = new TeamInfo();
Long newId = teamInfoMapper.insertDemo(teamInfo);
System.out.println("newId===" + teamInfo.getId());
必须传入 实体对象,使用 teamInfo.getId() 获取id;
===== tk.mybatis框架
需要在实体类 的ID 属性上 增加注解
@GeneratedValue(strategy = GenerationType.IDENTITY)
@GeneratedValue(strategy = GenerationType.IDENTITY)
@TableId(value = "id", type = IdType.AUTO)
private Long id;
本文介绍了MyBatis框架中插入数据时如何获取自增ID的三种方法:通过设置实体类属性、使用`<selectKey>`标签以及利用`useGeneratedKeys`属性。每种方法都在Java代码中展示了如何操作,并强调了关键点,如`keyProperty`的设置和`getId()`的使用。
2548

被折叠的 条评论
为什么被折叠?



