javaspring-bootspring-data-jpa

java.lang.NullPointerException: Cannot invoke because the return value of is null


I have the following Spring Data JPA repository.

@Query(value = """
      INSERT INTO users(id, customerId, locale) VALUES (:id, :customerId, :title, :locale)                                                                                                                                                     
            """, nativeQuery = true)
  void create(@Param("id") Long id,
              @Param("customerId") String customerId,
              @Param("title") String title,
              @Param("locale") String locale,

.........

public enum Title {
  CEO
}
...

public class Profile {
   private Title title;
   // getter/ setter 
}


profileRepository.create(
            profile.getId(),
            profile.getCustomerId(),
            Optional.of(profile.getTitle().name()).orElse(null)
            profile.getLocale())

When I have empty title I get error:

java.lang.NullPointerException: Cannot invoke "com.entity.Title.name()" because the return value of "com.entity.Profile.getTitle()" is null

How I allow the code to insert empty value and SQL query to insert NULL as a payload?


Solution

  • Replace Optional.of(profile.getTitle().name()).orElse(null) with Optional.ofNullable(profile.getTitle()).map(x->x.name()).orElse(null)