目录
Mysql设置id主键为自增
Mapper映射文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lele.dao.PersonMapper"><insert id="insertkey" parameterType="Person">
<selectKey keyProperty="id" order="AFTER" resultType="int">
select lAST_INSERT_ID()
</selectKey>
insert into person(id,name,address,age) values(#{id},#{name},#{address},#{age})
</insert>
<!-- <insert id="insertkey" parameterType="Person" keyProperty="id" useGeneratedKeys="true">
insert into person(id,name,address,age) values(#{id},#{name},#{address},#{age})
</insert>-->
</mapper>
keyproperty:数据表的字段和实体类的属性是对应的 自增长在实体类中的对应的属性就是keyproperty
order表示"select lAST_INSERT_ID()"是先执行还是后执行
测试类
public class Test01 {
@Test
public void selectKey(){
SqlSession session = MybatisUtil.getSession();
Person person = new Person(null, "乐乐2", "郑州", 19);
PersonMapper mapper = session.getMapper(PersonMapper.class);
int insertkey = mapper.insertkey(person);
System.out.println(person.getId());
}
插入后返回值为1表示插入成功 为0 表示插入失败
实体类.getId()获取获取自增主键的id值