以前,我具有以下代码结构:
存储库
public User findByEmail(EmailAddress email);
服务
@Override
public User findByEmail(String email) {
return userRepository.findByEmail(new EmailAddress(email));
}
@Modifying
@Transactional
@Override
public User add(User user) {
if (findByEmail(user.getEmail().toString()) == null) {
// Save the returned id into the entity
user = userRepository.saveAndFlush(user);
return user;
} else {
throw new EntityAlreadyExistsException();
}
}
现在我可以具有以下代码结构:
存储库
public Optional<User> findByEmail(EmailAddress email);
服务
@Override
public User findByEmail(String email) {
Optional<User> user = userRepository.findByEmail(new EmailAddress(email));
if (user.isPresent()) {
return user.get();
} else {
throw new EntityNotFoundException();
}
}
@Modifying
@Transactional
@Override
public User add(User user) {
try {
findByEmail(user.getEmail().toString());
throw new EntityAlreadyExistsException();
} catch (EntityNotFoundException e) {
// Save the returned id into the entity
user = userRepository.saveAndFlush(user);
return user;
}
}
我想知道移动到Optional和EntityNotFoundException返回的对象是否有意义吗?
作为一个旁注,为了记录服务使用情况,我还在服务接口中声明了抛出的异常:
public User update(Long id, User user) throws EntityNotFoundException;
这是要做的事吗?