簡體   English   中英

可選對象spring boot - 獲取對象字段

[英]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。 所以我感興趣的是有沒有使用可選的getter的解決方案,或者我需要使用其他方法來通過id查找Customer?

返回Optional<Customer> ,因為無法保證在數據庫中將有這樣的客戶具有所請求的ID。 它不是返回null,而只是意味着當ID不存在時, Optional.isPresent()將返回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'
}

或者,您可以嘗試回調樣式(使用Java 8 Lambda顯示):

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

值得注意的是,可以通過使用接口方法檢查ID的存在而無需實際檢索/加載實體:

boolean CrudRepository.existsById(ID id)

這樣可以節省實體負載,但仍需要數據庫往返。

嘗試使用另一種方法來查找客戶:

@Autowired
CustomerRepo repo;

Customer dbCustomer = repo.findOne(id);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM