- 写SQL,但不要自己插入主键值
- 配置
@Options(useGeneratedKeys=true, keyProperty="对象.属性")
这个的作用是设置是否使用
JDBC的getGenereatedKeys()
方法获取主键并赋值到keyProperty设置的对象的属性中,说白了就是把自增长的主键值赋值给对象相应的属性
- 在插入后,使用对象.主键属性的getXXId()方法 获取主键值
示例:
@Insert("INSERT INTO api(component, clientApi, scribeDescribe, clientApiVersion, invokeTimeout, authType, sessionRequire, openType) VALUES(#{api.component}, #{api.clientApi}, #{api.scribeDescribe}, #{api.clientApiVersion}, #{api.invokeTimeout}, #{api.authType}, #{api.sessionRequire}, #{api.openType})")
@Options(useGeneratedKeys = true, keyProperty = "api.apiId")
void add(@Param("api") Api api);
然后调用api.getApiId()即可
---------------------------------------xml-------------
<insert id="addUser" useGeneratedKeys="true" parameterType="com.lan.vote.model.User" keyProperty="id">
insert into User(name) values(#{name})
</insert>
User user = new User();
user.setUserName("chenzhou");
userDao.insertAndGetId(user);
//插入操作
Integer id = user.getUserId()
//直接获取主键id
System.out.println("返回的主键为:"+id);
-------------
public class User {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id= id;
}
//省略其它 get 和 set方法
}