Spring data jpa spring数据JPA optional.orelse无法正常工作
服务:Spring data jpa spring数据JPA optional.orelse无法正常工作,spring-data-jpa,Spring Data Jpa,服务: Country country = countryService.findCountryByName(DEFAULT_COUNTRY_NAME) .orElse(countryService.create(createCountryEntity())); 我不知道为什么countryService.findCountryByName(默认的国家名) .orElse(countryService.create(createCountryEntity
Country country = countryService.findCountryByName(DEFAULT_COUNTRY_NAME)
.orElse(countryService.create(createCountryEntity()));
我不知道为什么countryService.findCountryByName(默认的国家名)
.orElse(countryService.create(createCountryEntity())代码>始终进入orElse
块,即使我验证了调试器中存在第一部分
我怎么修理它
我不知道为什么[…]总是进入orElse区块,即使我验证了第一部分的存在
这就是Java的工作原理。
orElse
只是一种方法,而不是if条件或其他东西。
因此,将在调用它之前对其参数进行求值
你可能想要像这样的东西
@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;
}
您的dao和实体是什么样子的?我已经添加了实体和dao信息。
@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;
}
Country country = countryService
.findCountryByName(DEFAULT_COUNTRY_NAME)
.orElseGet(() -> countryService.create(createCountryEntity()));