JHipster在java代码中大量运用stream和Optional,使得代码简洁,运行效率高,下面总结了一些用例,基本涵盖了我们项目日常遇见的需求。
repository.findById(id).orElseThrow(() -> new BadRequestAlertException("error message!", null,"error_type"));
Optional.ofNullable(entity.getValue()).orElse(""))
Collectors的使用
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
查询当前用户id
String userId = SecurityUtils.getCurrentUserLogin().map(userRepository::findByUserName).map(Optional::get)
.map(ApplicationUser::getId).get();
在数据库中查询用户,如果存在,利用数据库查询结果计算并返回,若不存在抛出异常(或返回其它结果)。
public UserDetails loadUserByUsername(final String login) {
return userRepository.findOneByLogin(lowercaseLogin)
.map(user -> createSpringSecurityUser(lowercaseLogin, user))
.orElseThrow(() -> new UsernameNotFoundException("User " + lowercaseLogin + "
was not found in the database"));
}
private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) {
return new org.springframework.security.core.userdetails.User(user.getLogin(),
user.getPassword(),
grantedAuthorities);
}
根据当前登录用户名称进行数据库查询,若存在,对用户信息进行更新。
SecurityUtils.getCurrentUserLogin()
.flatMap(userRepository::findOneByLogin)
.ifPresent(user -> {
user.setFirstName(firstName);
user.setLastName(lastName);
if (email != null) {
user.setEmail(email.toLowerCase());
}
user.setLangKey(langKey);
user.setImageUrl(imageUrl);
userRepository.save(user);
this.clearUserCaches(user);
log.debug("Changed Information for User: {}", user);
});
根据字符串列表中的字符串进行数据库查询,以数据库查询结果创建新的对象列表
userDTO.getAuthorities().stream()
.map(authorityRepository::findById)
.filter(Optional::isPresent)
.map(Optional::get)
.forEach(managedAuthorities::add);
仅当数据库查询用户存在时,清空缓存,并返回用户传输对象。
Optional.of(userRepository
.findById(userDTO.getId()))
.filter(Optional::isPresent)
.map(Optional::get)
.map(user -> {
this.clearUserCaches(user);
return user;
})
.map(UserDTO::new);
另外,在controller中大胆使用Optional作为返回对象,前端无需做任何特殊处理。
UserResource:
@GetMapping("/users/{login:" + Constants.LOGIN_REGEX + "}")
public ResponseEntity<UserDTO> getUser(@PathVariable String login) {
log.debug("REST request to get User : {}", login);
return ResponseUtil.wrapOrNotFound(
userService.getUserWithAuthoritiesByLogin(login)
.map(UserDTO::new));
}
UserService:
public Optional<User> getUserWithAuthoritiesByLogin(String login) {
return userRepository.findOneByLogin(login);
}
Good Luck,
Cheers!