java.lang.NullPointerException:无法调用,因为 的返回值为 null

问题描述 投票:0回答:1

我有以下 Spring Data JPA 存储库。

@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())

当我有空时

title
我收到错误:

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

如何允许代码插入空值和 SQL 查询插入 NULL 作为有效负载?

java spring-boot spring-data-jpa
1个回答
0
投票

Optional.of(profile.getTitle().name()).orElse(null)
替换为
Optional.ofNullable(profile.getTitle()).map(x->x.name()).orElse(null)

© www.soinside.com 2019 - 2024. All rights reserved.