0

According to Spring Data JPA Property Expressions a query in my UserExtraRepository.java in jhipster (4.14.4) with

UserExtra findOneByUserLogin(String login)

should return an UserExtra-Object, which has an 1:1-relationship with User (jhi_user) where the user is recognized by its login String.

But I get a Null Pointer Exception, when I try to use it in the POST-method of anothers entity resource-class (PartyFoodResource.java):

// set UserExtra from logged in User (jhi_user) as Owner of PartyFood-Object
    String userLogin = SecurityUtils.getCurrentUserLogin().get();
    if(userLogin == ""){
        throw new IllegalArgumentException("userLogin can not be empty!");
    }
    log.debug("userLogin is '" + userLogin + "'");
    UserExtra userExtra = new UserExtra();
    userExtra = userExtraService.findOneByUserLogin(userLogin);
    log.debug("userExtra gefunden : {}", userExtra);
    partyFood.setUserExtra(userExtra);

    PartyFood result = partyFoodService.save(partyFood);

Can you give me a hint, what I don't understand right now?


Edit: If I try the answer from agilob, I get a Null Pointer Exception, too, with final Optional<User> isUser = userService.getUserWithAuthorities();

If I try

    String loggedInUser = SecurityUtils.getCurrentUserLogin().get();
    log.debug("user gefunden : {}", loggedInUser);

    final Optional<User> isUser = userService.getUserWithAuthoritiesByLogin(loggedInUser);

I get a debug log entry with the login String, but still a Null Pointer Exception with userService.getUserWithAuthoritiesByLogin(loggedInUser);

Jochen Haßfurter
  • 875
  • 2
  • 13
  • 27

1 Answers1

0

I have erased my code in PartyFoodResource.java and pasted it into PartyFoodServiceImpl.java. It is working now with:

/**
 * Save a partyFood.
 *
 * @param partyFood the entity to save
 * @return the persisted entity
 */
@Override
public PartyFood save(PartyFood partyFood) {
    log.debug("Request to save PartyFood : {}", partyFood);

 /**
 * Add the logged in user into a relation to newly created records of the entity PartyFood.
 * The user will be the owner of the PartyFood.
 */

    final Optional<User> isUser = userService.getUserWithAuthorities();
    if (!isUser.isPresent()) {
        log.debug("User is not logged in");
    }

    final User user = isUser.get();

    UserExtra userExtra = new UserExtra();
    userExtra = userExtraService.findOneByUserId(user.getId());
    log.debug("userExtra gefunden : {}", userExtra.getUser().getLogin());
    partyFood.setUserExtra(userExtra);

    PartyFood result = partyFoodRepository.save(partyFood);
    partyFoodSearchRepository.save(result);
    return result;
}
Jochen Haßfurter
  • 875
  • 2
  • 13
  • 27