背景
在新增一条记录时,数据库中有create_id字段,在新增的Service层每次都需要setCreateId和setUpdateId有点麻烦能不能再mybatis的SQL语句中从ThreadLocal中获取当前的用户ID,而不用每次新增去setCreateId了。
代码
注意事项:getUserId()方法必须是静态方法。
package com.zhao.UserServer;
@Service
public class UserServer {
@Resource
private UserMapper userMapper;
private static ThreadLocal<Long> userIdThreadLocal=new ThreadLocal<~>();
public void setUserId(Long userId) {
userIdThreadLocal.set(userId);
}
public static Long getUserId() {
return userIdThreadLocal.get();
}
public void insert(User user) {
int i = userMapper.insert(user);
}
SQL语句
<insert id="insert" keyProperty="id" useGeneratedKeys="true">
insert into user(id,name,password) values (${@com.zhao.UserServer@getUserId()},#{name},#{password})
</insert>