我有以下 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 作为有效负载?
将
Optional.of(profile.getTitle().name()).orElse(null)
替换为 Optional.ofNullable(profile.getTitle()).map(x->x.name()).orElse(null)