首页 > 解决方案 > 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

我如何解决它?

标签: spring-data-jpa

解决方案


我不知道为什么 [...] 总是进入 orElse 块,即使我验证了第一部分存在

这就是 Java 的工作原理。 orElse只是一种方法,而不是 if 条件或其他东西。因此,它的参数将在它被调用之前被评估。

你可能想要类似的东西

Country country = countryService
        .findCountryByName(DEFAULT_COUNTRY_NAME)
        .orElseGet(() -> countryService.create(createCountryEntity()));

推荐阅读