因为公司的表用的是自增id,而不是UUID,所以在好多时候都需要返回新插入的数据的id,所以在网上搜了一些方法,大部分都是用的xml方式来写的sql,不过本人是用的注解方式,方法比较少,所以写这篇文章来记录一下,下面是详细的方法。
先说注解的方式,我的代码习惯一般是写一个dao类(Interface,不是class类),然后写一个实现类;可能有些人是把sql直接写在了注解里边,但是方法都是一样的。
直接上代码
@Mapper
public interface CustomerDao {
@InsertProvider(type = CustomerProvider.class, method = "saveInfoSql")
@Options(useGeneratedKeys=true, keyProperty="customerModule.id", keyColumn="id")
Boolean saveInfo (@Param("customerModule") CustomerModule customerModule);
@UpdateProvider(type = CustomerProvider.class, method = "updateInfoSql")
Boolean updateInfo (@Param("customerModule") CustomerModule customerModule);
}
使用注解 @Options 来指定开启自增主键功能,并且指定主键名称。
useGeneratedKeys=true 是开启改功能;
keyProperty="customerModule.id" 是指定传入的实体对应表的主键的字段;
keyColumn="id" 是指定表内的主键字段。
这样就可以了,在你调用dao方法后直接从你传入dao方法的实体内就可以拿到对应的id了。
Boolean flag = customerDao.saveInfo(customerModule);
Integer id = customerModule.getId();
例如:
我传入的是CustomerModule实体,直接用改实体的get方法getId()就可以。
还有一种是使用xml方式来写sql,方法如下内容转自 十七年蝉 链接:https://www.cnblogs.com/zhuzhen/p/6894995.html
在开发中碰到用户注册的功能需要用到用户ID,但是用户ID是数据库自增生成的,这种情况上网查询后使用下面的方式配置mybatis的insert语句可以解决
<insert id="insert" keyProperty="id" useGeneratedKeys="true"
parameterType="com.demo.domain.User">
insert into User_t(name,age,addr) values(#{name},#{age},#{addr})
</insert>
注意:数据库中该表表的主键ID是自增的。
通过插入数据的对象可获得该对象的id。
@Override
public int insert(User user) {
int insertNum = Integer.parseInt(userMapper.insert(user) + "");
Long id = user.getId();//该对象的自增ID
return insertNum;
}