企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
**方式一,useGeneratedKeys** **1.UserMapper.java** ~~~ //新增并获取主键值 int save1(User u); ~~~ **2.UserMapper.xml** ~~~ <!--useGeneratedKeys:是否使用自增主键 --> <!--keyProperty:对应到实体属性中--> <insert id="save1" parameterType="User" useGeneratedKeys="true" keyProperty="id"> insert into t_user(u_name,u_password) values(#{name},#{password}) </insert> ~~~ **3.测试代码** ~~~ @Test public void save1(){ UserMapper mapper = session.getMapper(UserMapper.class); User u = new User(); u.setName("test"); u.setPassword("hello"); System.out.println(mapper.save1(u)); System.out.println(u.getId()); } ~~~ **方式二,使用select LAST\_INSERT\_ID()** **1.UserMapper.java** ~~~ //新增并获取主键值 int save1(User u); ~~~ **2.UserMapper.xml** ~~~ <!--keyColumn:主键对应数据库的字段--> <!--keyProperty:主键对应实体属性--> <!--order:Insert语句之前还是之后--> <!--resultType:主键值类型--> <insert id="save1" parameterType="User"> <selectKey keyColumn="u_id" keyProperty="id" order="AFTER" resultType="int"> select LAST_INSERT_ID() </selectKey> insert into t_user(u_name,u_password) values(#{name}, #{password}) </insert> ~~~ **3.测试代码** ~~~ @Test public void save1(){ UserMapper mapper = session.getMapper(UserMapper.class); User u = new User(); u.setName("test11"); u.setPassword("hello"); System.out.println(mapper.save1(u)); System.out.println(u.getId()); } ~~~