我是春季新來的,嘗試通過創建小專案來提高我的技能。在我的新應用程式中,我想對 accountNumber 進行唯一性檢查,不幸的是我沒有成功。我想應用 isPresent() 方法,但是當我呼叫它時它不存在。如果我得到幫助,將不勝感激。
以下是我應用邏輯的服務類,我還提到了 Rep. & Ent。類供您參考。我在第 3 行中應用了唯一條件,其中 find ***if ..... ***。
我發現了類似的問題,但此堆疊中的解決方案與我喜歡的方式不匹配,我想使用 JPA 而不是 JPQL。
賬戶服務
@Autowired
private AccountRepository accountRepository;
@Transactional
public ResponseEntity<Object> addAccount(CurrentAccount currentAccount){
**if(currentAccount.getAccountNumber().is)**
accountRepository.save(currentAccount);
return ResponseEntity.ok("Account Accepted");
}
活期賬戶
public class CurrentAccount {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name = "account_number")
private String accountNumber;
@Column(name = "account_balance")
private Integer accountBalance;
帳戶庫
public interface AccountRepository extends JpaRepository<CurrentAccount, Long> {
Optional<CurrentAccount> findByAccountNumber(String accountNumber);
}
uj5u.com熱心網友回復:
只需使用existsByJPA 的方法,就像這樣。如果CurrentAccount存在與給定的帳號,則回傳 true 。
boolean existsCurrentAccountByAccountNumber(String accountNo);
如果您想檢查多個引數,請執行此操作。
boolean existsCurrentAccountByAccountNumberAndName(String accountNo, String name);
服務
@Transactional
public ResponseEntity<Object> addAccount(CurrentAccount currentAccount){
if(accountRepository.existsCurrentAccountByAccountNumberAndName(currentAccount.getAccountNumber(), currentAccount.getName())){
return new ResponseEntity<>(HttpStatus.BAD_REQUEST); // or anything you want to do if record is already exists.
}else{
accountRepository.save(currentAccount);
return ResponseEntity.ok("Account Accepted");
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/326748.html
上一篇:如何在SpringBoot中獲取json格式的選擇資料
下一篇:以反應方式一次發送一個物件串列
