好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

MyBatis获取数据库自生成的主键Id详解及实例代码

MyBatis获取数据库自生成的主键Id详解及实例代码

在使用MySQL数据库时我们一般使用数据库的自增主键自动产生主键。如果在插入主表时,我们需要同时插入从表的数据,这时我们通常需要知道主表插入时自动产生的主键Id值。

下面介绍使用MyBatis进行插入时,如何同时获取数据库自生成的主键:

1、XML配置文件

?

1

2

3

< insert id = "insert" parameterType = "Person" useGeneratedKeys = "true" keyProperty = "id" >

     insert into person(name,pswd) values(#{name},#{pswd})

</ insert >

2、Mapper中的方法

?

1

int insert (Person person);

注意在调用这个方法时,返回的int值并不是主键,而是插入的记录数。主键id会被赋值到输入的person对象里,自动赋值给person对象的id属性。比如:

?

1

2

3

4

5

Person person = new Person( "name" , "psw" );

//num是插入的记录数

int num = PersonMapper.insert(person);

//person对象的id属性会变成自生成的id

int id = person.getId();

 感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

查看更多关于MyBatis获取数据库自生成的主键Id详解及实例代码的详细内容...

  阅读:33次