spring-data-jpa - spring data JPA optional.orelse 无法正常工作
问题描述
Country country = countryService.findCountryByName(DEFAULT_COUNTRY_NAME)
.orElse(countryService.create(createCountryEntity()));
服务:
public Optional<Country> findCountryByName(String name) {
return dao.findByNameIgnoreCase(name);
}
@Transactional(propagation = Propagation.REQUIRED)
public Country create(Country country) {
return dao.save(country);
}
道:
@Transactional
public interface CountryDao extends JpaRepository<Country, Integer> {
Optional<Country> findByNameIgnoreCase(String name);
}
实体
@Entity
@Table(name = "country")
@Data
public class Country {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "country_id", updatable = false)
@JsonIgnore
private int id;
@Column(name = "country_name")
@NotNull
@Size(min = 4, max = 100)
private String name;
}
即使我验证了调试器中存在第一部分,我也不知道为什么countryService.findCountryByName(DEFAULT_COUNTRY_NAME)
.orElse(countryService.create(createCountryEntity()));
总是进入块。orElse
我如何解决它?
解决方案
我不知道为什么 [...] 总是进入 orElse 块,即使我验证了第一部分存在
这就是 Java 的工作原理。
orElse
只是一种方法,而不是 if 条件或其他东西。因此,它的参数将在它被调用之前被评估。
你可能想要类似的东西
Country country = countryService
.findCountryByName(DEFAULT_COUNTRY_NAME)
.orElseGet(() -> countryService.create(createCountryEntity()));
推荐阅读
- python - 如何在按钮命令中设置变量以在创建多个按钮的循环中拥有按钮的文本?
- oracle - 根据表中的现有数字查找特定数字
- php - wordpress 中的 date.php 和 archive.php
- bash - fontforge 如何在命令行中通过字符名或字符 unicode 导出/导入 svg 文件
- c# - 如何使用 xamarin 表单更新 firebase 实时数据中的特定数据?
- javascript - 按度旋转图像并裁剪
- python - 是否可以将 ttk 笔记本选项卡的名称向左对齐?
- go - pq QueryRow 扫描失败,内存地址无效或指针取消引用
- python - 在 docker 中安装 0.82 版的 Poppler utils
- oracle - oracle 中的更新触发器问题