简体   繁体   中英

How to put check if record already exist - spring boot

I'm new in spring & try to enhance my skill by creating little projects. In my new app I'd like to put uniqueness check on accountNumber, unfortunately I did not get success. I'd like to apply isPresent() method but it doesn't exist when I call it. Grateful if I get help.

Following is my Service class where I apply logics, I also mention Rep. & Ent. classes for your reference. I apply unique condition in 3rd line where find ***if ..... ***.

I've found similar question but the solution in this stack doesn't match with the way I like to do, I'd like to use JPA not JPQL.

AccountService

@Autowired
  private AccountRepository accountRepository;

@Transactional
  public ResponseEntity<Object> addAccount(CurrentAccount currentAccount){
    **if(currentAccount.getAccountNumber().is)**
    accountRepository.save(currentAccount);
    return ResponseEntity.ok("Account Accepted");
} 

CurrentAccount

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;

AccountRepository

public interface AccountRepository extends JpaRepository<CurrentAccount, Long> {
    Optional<CurrentAccount> findByAccountNumber(String accountNumber);
}

Simply use existsBy method of JPA, Something like this. It returns true, if the CurrentAccount exists with the given account number.

 boolean existsCurrentAccountByAccountNumber(String accountNo);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM