SelectKey返回最近插入的id
一、第一种使用实体类对象
1.sql获取
<insert id="addUser" >
insert into user (username,password,name,create_time,sex,phone,department,company,address)
values(#{username},#{password},#{name},#{createTime},#{sex},#{phone},#{department},#{company},#{address})
<selectKey keyProperty="id" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
</insert>
或者
<!-- keyProperty对应的是javabean,keyColumn对应的是数据库中,自增属性的数据库id赋给javabean里的id -->
<insert id="add" parameterType="net.xdclass.online_class.domain.Video"
useGeneratedKeys="true" keyProperty="id" keyColumn="id" >
2.测试数据
@Autowired
UserMapper userMapper;
@Test
void test1(){
User user = new User();
user.setName("盖亚");
userMapper.addUser(user);
System.out.println(user.getId());
}
3.结果截图
二、第二种使用Map
xml中
<insert id="insertMessageType" parameterType="java.util.HashMap">
insert into n_message_type values (
null,
#{notificationType}
)
<selectKey keyProperty="id" resultType="java.lang.Integer">
SELECT LAST_INSERT_ID()
</selectKey>
</insert>
mapper中
Integer insertMessageType(HashMap<String, Object> param);
2.测试数据
HashMap<String, Object> stringIntegerHashMap = new HashMap<String, Object>();
stringIntegerHashMap.put("notificationType",type);
messageMapper.insertMessageType( stringIntegerHashMap);
typeId = (Integer) stringIntegerHashMap.get("id");
3.结果截图