@Service
@Slf4j
public class UserServiceImpl implements IUserService {
...
@Override
public Users userLogin(UserRequestDTO userRequestDTO) throws Exception {
log.info("======用户登录请求:{}", userRequestDTO);
Example example = new Example(Users.class);
val condition = example.createCriteria();
condition.andEqualTo("username", userRequestDTO.getUsername());
condition.andEqualTo("password", MD5GeneratorTools.getMD5Str(userRequestDTO.getPassword()));
val user = this.usersMapper.selectOneByExample(example);
log.info("======用户登录处理结果:{}", user);
return user;
}
}
Error Tips:
这里有一个小小的坑点,大家一定要注意,在使用selectOneByExample()查询的时候,该方法传入的参数一定注意是tk.mybatis.mapper.entity.Example实例,而不是tk.mybatis.mapper.entity.Example.Criteria,否则会报动态SQL生成查询错误,信息如下:
org.mybatis.spring.MyBatisSystemException: nested exception is org.apache.ibatis.reflection.ReflectionException: There is no getter for property named 'distinct' in 'class tk.mybatis.mapper.entity.Example$Criteria'
at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:92)
at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:440)
at com.sun.proxy.$Proxy106.selectOne(Unknown Source)
at org.mybatis.spring.SqlSessionTemplate.selectOne(SqlSessionTemplate.java:159)
at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:87)
at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:93)
at com.sun.proxy.$Proxy109.selectOneByExample(Unknown Source)
at com.liferunner.service.impl.UserServiceImpl.userLogin(UserServiceImpl.java:80)
...
新人在写代码的时候,特别容易在上一行写了查询变量,下一行就直接开用了,越是简单的错误越是让人无从下手。
public Users findUserByUserName(String username) {
// 构建查询条件
Example example = new Example(Users.class);
val condition = example.createCriteria()
.andEqualTo("username", username);
return this.usersMapper.selectOneByExample(example);
}
@Transactional(propagation = Propagation.REQUIRED)
@Override
public Users createUser(UserRequestDTO userRequestDTO) throws Exception {
log.info("======begin create user : {}=======", userRequestDTO);
val user = Users.builder()
.id(sid.next()) //生成分布式id
.username(userRequestDTO.getUsername())
.password(MD5GeneratorTools.getMD5Str(userRequestDTO.getPassword()))
.birthday(DateUtils.parseDate("1970-01-01", "yyyy-MM-dd"))
.nickname(userRequestDTO.getUsername())
.face(this.FACE_IMG)
.sex(SexEnum.secret.type)
.createdTime(new Date())
.updatedTime(new Date())
.build();
this.usersMapper.insertSelective(user);
log.info("======end create user : {}=======", userRequestDTO);
return user;
}
一旦遇到了问题之后,我们往往不知道到底是哪里出现了错误,这个时候我们的SQL是否有问题我们也不知道,因此,接下来我们来配置一种可以让我们看到SQL的小实现:
1.设置日志配置(如图)
log4j.properties
2.修改mybatis配置(log-impl: org.apache.ibatis.logging.stdout.StdOutImpl)
mybatis
3.SELECT效果演示
result
4.INSERT效果演示
INSERT
从上图可以看出控制台JDBC操作进行了2次,其实第一次是对我们的用户名进行校验。第二次INSERT是真实的插入。