MySQL和MSSQL返回主键方法
在personMap.xml中
<insert id="addPerson" parameterType="orm.Person" keyProperty="id" useGeneratedKeys="true">
insert into Person (name,age,gender) values (#{name},#{age},#{gender})
</insert>
调用插入方法,将mybatis返回的自动增长ID自动返回给id属性
SqlSession session =DBUtils.getSqlSession();
Person p=new Person();
p.setName("caoyc");
p.setAge((byte)18);
p.setGender("男");
System.out.println(session.insert("orm.personMapper.addPerson",p));;
session.commit();
session.close();
System.out.println(p.getId());
通过实体对象p.getId():就可以获取插入后该记录的id了
Oracle数据
<insert id="addPerson" parameterType="orm.Person" >
<selectKey resultType="java.long.Integer" keyProperty="id" order="BEFORE">
select idauto.nextval from dual
</selectKey>
insert into Person (id,name,age,gender) values (#{id},#{name},#{age},#{gender})
</insert>