之前insert测试中的new User()我们没给id我们来输出看一下
@Testpublic void testInsertUsers() throws ParseException {Users users = new Users("李明", sf.parse("2001-02-05"), "1", "大兴");int num = uMapper.insertUsers(users);System.out.println(num);sqlSession.commit();System.out.println(users);}
Users{id=null, userName='李明', birthday=Mon Feb 05 00:00:00 CST 2001, sex='1', address='大兴'}
当然,你要重写写Users.java中的toString()
<insert id="insertUsers" parameterType="users">
<selectKey keyProperty="id" resultType="int" order="BEFORE">
select last_insert_id()
</selectKey>
insert into users(username,birthday,sex,address) values(#{userName},#{birthday},#{sex},#{address})
</insert>
再来添加一条数据
@Test
public void testInsertUsers() throws ParseException {
Users users = new Users("小明", sf.parse("2001-02-05"), "1", "大兴");
int num = uMapper.insertUsers(users);
System.out.println(num);
sqlSession.commit();
System.out.println(users);
}
Users{id=0, userName='小明', birthday=Mon Feb 05 00:00:00 CST 2001, sex='1', address='大兴'}
<insert id="insertUsers" parameterType="users">
<selectKey keyProperty="id" resultType="int" order="AFTER">
select last_insert_id()
</selectKey>
insert into users(username,birthday,sex,address) values(#{userName},#{birthday},#{sex},#{address})
</insert>
@Test
public void testInsertUsers() throws ParseException {
Users users = new Users("小明1", sf.parse("2001-02-05"), "1", "大兴");
int num = uMapper.insertUsers(users);
System.out.println(num);
sqlSession.commit();
System.out.println(users);
}
Users{id=33, userName='小明1', birthday=Mon Feb 05 00:00:00 CST 2001, sex='1', address='大兴'}
**selectKey**标签的参数详解
- keyProperty: Users对象的哪个属性来接返回的主键值
- resultType: 返回的主键类型
- order: 在插入语句执行前,还是执行后返回主键的值
