Java 可选对象spring启动-获取对象字段
我已经定义了客户实体Java 可选对象spring启动-获取对象字段,java,spring-boot,jpa,crud,Java,Spring Boot,Jpa,Crud,我已经定义了客户实体 @Entity @Table(name = "customer") public class Customer { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Long id; @Column(name = "name") private String name; public Long getId
@Entity
@Table(name = "customer")
public class Customer {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
积垢
public interface CustomerRepo extends CrudRepository<Customer, Long> {
}
公共接口CustomerRepo扩展了Crudepository{
}
如果我使用CustomerRepo.findById方法查找客户
@Autowired
CustomerRepo repo;
Optional<Customer> dbCustomer = repo.findById(id);
@Autowired
客户回购;
可选的dbCustomer=repo.findById(id);
我怎样才能知道那个顾客的名字。我不能用getter。
所以我感兴趣的是,有没有使用可选getter的解决方案,或者我需要使用其他方法通过id查找客户?尝试使用其他方法查找客户:
@Autowired
CustomerRepo repo;
Customer dbCustomer = repo.findOne(id);
Optional
返回,因为不能保证数据库中会有这样一个具有请求ID的客户。
它不是返回null,而是意味着当ID不存在时,Optional.isPresent()
将返回false
根据API文档():
或者,您可以尝试回调样式(如Java 8 Lambda所示):
这可以节省实体负载,但仍然需要数据库往返。在repo中添加一个方法,用于按id查找客户,然后您可以像这样使用
customer dbCustomer=repo.findById(id)代码>我尝试并获得“不兼容的类型。必需:com.fitnet.phonqpon.models.Customer-Found:java.util.Optional”。。。。。。。。但是如果我添加Customer findById(Long id);方法在CustomerRepo接口内部,我在com.fitnet.phonqpon.repositories.CustomerRepo中得到“'findById(Long)”与在org.springframework.data.repository.crudepository中的“findById(ID)”冲突;试图使用不兼容的返回类型”您可以将主键的字段名更改为customerId或其他内容,并在repo中添加一个方法,如findByCustomerId(Long id)
id是我的主键的字段名谢谢Thomas。这对我很有帮助。
Returns:
the entity with the given id or Optional#empty() if none found
Optional<Customer> dbCustomer = repo.findById(id);
if(dbCustomer.isPresent()) {
Customer existingCustomer = dbCustomer.get();
String nameWeWanted = existingCustomer.getName();
//operate on existingCustomer
} else {
//there is no Customer in the repo with 'id'
}
Optional<Customer> dbCustomer = repo.findById(id);
dbCustomer.ifPresent(existingCustomer -> {
String nameWeWanted = existingCustomer.getName();
//operate on existingCustomer
});
boolean CrudRepository.existsById(ID id)