用注解的方式实现Mybatis插入数据时返回自增的主键Id

https://blog.csdn.net/ylforever/article/details/79191182

我们在数据库表设计的时候,一般都会在表中设计一个自增的id作为表的主键。这个id也会关联到其它表的外键。

这就要求往表中插入数据时能返回表的自增id,用这个ID去给关联表的字段赋值。下面讲一下如何通过注解的方式实现插入数据时返回自增Id。

二、设计数据库表
CREATE TABLE `tbl_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL DEFAULT '',
`age` int(4) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
1
2
3
4
5
6
三、设计Java bean对象
public class User
{
private int userId = -1;

private String name = "";

private int age = -1;

@Override
public String toString()
{
return "name:" + name + "|age:" + age;
}

public int getUserId()
{
return userId;
}

public void setUserId(int userId)
{
this.userId = userId;
}

public String getName()
{
return name;
}

public void setName(String name)
{
this.name = name;
}

public int getAge()
{
return age;
}

public void setAge(int age)
{
this.age = age;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
四、添加mapper接口
@Mapper
public interface UserMapper
{
@Insert("insert into tbl_user (name, age) values (#{name}, #{age})")
@Options(useGeneratedKeys=true, keyProperty="userId", keyColumn="id")
void insertUser(User user);
}
---------------------
作者:Elon.Yang
来源:CSDN
原文:https://blog.csdn.net/ylforever/article/details/79191182
版权声明:本文为博主原创文章,转载请附上博文链接!

原文地址:https://www.cnblogs.com/yuluoxingkong/p/10244799.html