这篇文章介绍了mybatis的主键返回方法 一.需求分析 当我们表的主键设置为自增,且插入数据后需要主键id时,就要使用主键返回的方法,来获取当前插入数据的主键。 表如下: 二.主键返回 1.使用
这篇文章介绍了mybatis的主键返回方法
当我们表的主键设置为自增,且插入数据后需要主键id时,就要使用主键返回的方法,来获取当前插入数据的主键。
表如下:
< selectKey >标签,keyProperty:设置为目标属性,resultType:设置返回值类型,order:值为after,before
after: sql之后执行,before: sql之前执行
示例:
StudentMapper接口
public interface StudentMapper { int insert(Student student);}
StudentMapper.xml代码
<insert id="insert" parameterType="com.hem.pojo.Student"> <selectKey keyProperty="id" resultType="int" order="AFTER"> select last_insert_id() </selectKey> insert into student (name,email,age) values (#{name},#{email},#{age}); </insert>
test代码:
@Test public void testInsert() throws ioException { //使用文件流读取核心配置文件SqlMapConfig.xml InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml"); //创建SqlSessionFactory工厂 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); //取出sqlSession对象 SqlSession sqlSession = factory.openSession(); //完成查询操作 StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); Student student = new Student("小白","12321",99); int num = studentMapper.insert(student); System.out.println(student.getId()); sqlSession.commit(); //关闭sqlSession sqlSession.close(); }
测试结果:
设置 useGeneratedKeys=”true”,然后再把 keyProperty 设置为目标属性就 OK 了
示例:
StudentMapper接口
public interface StudentMapper { int insert(Student student);}
StudentMapper.xml代码:
<insert id="insert" parameterType="com.hem.pojo.Student" useGeneratedKeys="true" keyProperty="id"> insert into student (name,email,age) values (#{name},#{email},#{age}); </insert>
test代码:
@Test public void testInsert() throws IOException { //使用文件流读取核心配置文件SqlMapConfig.xml InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml"); //创建SqlSessionFactory工厂 SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in); //取出sqlSession对象 SqlSession sqlSession = factory.openSession(); //完成查询操作 StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class); Student student = new Student("小白","12321",99); int num = studentMapper.insert(student); System.out.println(student.getId()); sqlSession.commit(); //关闭sqlSession sqlSession.close(); }
测试结果:
202210161704日
来源地址:https://blog.csdn.net/qq_53843555/article/details/127347086
--结束END--
本文标题: MyBatis主键返回
本文链接: https://lsjlt.com/news/397220.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-10-23
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0