useGeneratedKeys可以让mybatis获取生成的key keyProperty可以让mybatis将获取的key赋值给参数的指定字段
1、实体类User的书写
package com.yunhe.pojo;
import java.util.Date;
import java.util.Objects;
public class User {
private Integer id;
private String name;
private Double sal;
private Date birthday;
public User() {
}
public User(Integer id, String name, Double sal, Date birthday) {
this.id = id;
this.name = name;
this.sal = sal;
this.birthday = birthday;
}
public User(String name, Double sal, Date birthday) {
this.name = name;
this.sal = sal;
this.birthday = birthday;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getSal() {
return sal;
}
public void setSal(Double sal) {
this.sal = sal;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(id, user.id) && Objects.equals(name, user.name) && Objects.equals(sal, user.sal) && Objects.equals(birthday, user.birthday);
}
@Override
public int hashCode() {
return Objects.hash(id, name, sal, birthday);
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", sal=" + sal +
", birthday=" + birthday +
'}';
}
}
2、UserMapper接口的书写
public interface UserMapper {
// 插入数据
Integer insert(User user);
}
3、UserMapper.xml的书写
<insert id="insert" useGeneratedKeys="true" keyProperty="id">
insert into t_user(`name`,sal,birthday) values (#{name},#{sal},#{birthday})
</insert>
4、测试类书写
public class Test {
public static void main(String[] args) {
SqlSessionFactory sqlSessionFactory = MybatisUtil.getSqlSessionFactory();
SqlSession session = sqlSessionFactory.openSession();
UserMapper mapper = session.getMapper(UserMapper.class);
User user = new User("李四", 200.0, new Date());
Integer i = mapper.insert(user);
System.out.println(user.getId());
session.commit();
}
}