可选对象spring boot - 获取对象字段

Ant*_*reš 2 java jpa crud spring-boot

我已经定义了客户实体

@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;
    }
}
Run Code Online (Sandbox Code Playgroud)

和CrudRepository

public interface CustomerRepo extends CrudRepository<Customer, Long> {
}
Run Code Online (Sandbox Code Playgroud)

如果我使用CustomerRepo.findById方法来查找客户

@Autowired
CustomerRepo repo;

Optional<Customer> dbCustomer = repo.findById(id);
Run Code Online (Sandbox Code Playgroud)

我怎样才能得到该客户的名字.我当时不能使用getter.所以我感兴趣的是有没有使用可选的getter的解决方案,或者我需要使用其他方法来通过id查找Customer?

Tho*_*bul 10

Optional<Customer>返回,因为不能保证在数据库中会有这样一个具有所请求ID的客户.它不是返回null,而只是意味着Optional.isPresent()当ID不存在时将返回false.

根据API文档(https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html#findById-ID-):

Returns:
the entity with the given id or Optional#empty() if none found

因此,您可能只想使用方法Optional来检查它是否包含Customer(即存在该ID的Customer),然后获取如下名称:

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'
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以尝试回调样式(使用Java 8 Lambda显示):

Optional<Customer> dbCustomer = repo.findById(id);
dbCustomer.ifPresent(existingCustomer -> {
    String nameWeWanted = existingCustomer.getName();
    //operate on existingCustomer
});
Run Code Online (Sandbox Code Playgroud)

值得注意的是,可以通过使用接口方法检查ID的存在而无需实际检索/加载实体:

boolean CrudRepository.existsById(ID id)
Run Code Online (Sandbox Code Playgroud)

这样可以节省实体负载,但仍需要数据库往返.