I have a service in Springboot and I want to get an optional entity and to check if is not null to do something after.
User repository class
public interface UserRepository extends JpaRepository<UserEntity, Long> {
Optional<UserEntity> findByLastName(String lastName);
}
Role repository class
public interface RoleRepository extends JpaRepository<RoleEntity, Long> {
Optional<RoleEntity> findByName(String name);
}
How can I write properly this code below?
public UserEntityDto addRoleToUser(String username, String rolename) {
Optional<UserEntity> usrDb = userRep.findByLastName(username);
Optional<RoleEntity> roleDb = roleRep.findByName(rolename);
UserEntity userEntity = usrDb.orElse(null);
RoleEntity roleEntity = roleDb.orElse(null);
if (userEntity != null && roleEntity != null) {
userEntity.getRoles().add(roleEntity);
}
return userEntityMapper.fromUserEntity(userEntity);
}