Home > Software engineering >  How to put check if record already exist - spring boot
How to put check if record already exist - spring boot

Time:10-20

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

CodePudding user response:

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);

If you want to check with more than one parameter then do this.

boolean existsCurrentAccountByAccountNumberAndName(String accountNo, String name);

Service

@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");
   }
} 
  • Related