可选对象 spring 引导 - 获取对象字段

Optional objects spring boot - get object fields

我已经定义了客户实体

@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;
    }
}

和 CrudRepository

public interface CustomerRepo extends CrudRepository<Customer, Long> {
}

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

@Autowired
CustomerRepo repo;

Optional<Customer> dbCustomer = repo.findById(id);

我怎样才能得到那个客户的名字。那时我不能使用 getter。 所以我很感兴趣是否有任何使用可选的 getters 的解决方案,或者我需要使用其他方法通过 id 查找客户?

尝试使用其他方法寻找客户:

@Autowired
CustomerRepo repo;

Customer dbCustomer = repo.findOne(id);

Optional<Customer>是return编辑的,因为不能保证数据库中一定会有这样的客户,要求的ID。 而不是 returning null 它只是意味着当 ID 不存在时 Optional.isPresent() 将 return 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 上的方法来检查它是否包含客户(即存在具有该 ID 的客户),然后像这样获取名称:

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'
}

或者您可以尝试回调方式(显示为 Java 8 Lambda):

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

值得注意的是,可以通过使用接口方法 retrieving/loading 来检查 ID 是否存在,实际上 retrieving/loading 实体:

boolean CrudRepository.existsById(ID id)

这节省了实体负载,但仍需要数据库往返。