Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading