How to Check If a Record Exists Using Jpa

How to check if a record exists using JPA

If you just want to know whether the object exists, send a SELECT COUNT to your database. That will return 0 or 1.

The cost of the exception handling isn't that big (unless you do that millions of times during a normal operation), so I wouldn't bother.

But the code doesn't really reflect your intention. Since getSingleResult() calls getResultList() internally, it's clearer like so:

public boolean objExists(...) {
return getResultList(...).size() == 1;
}

If you query by object id and you have caching enabled, that will become a simple lookup in the cache if the object has already been loaded.

How do i check if a record already exists in table in springboot JPA?

Implement a select method in QuestionDetailsRepository as below. Add all the criteria which make a record unique. I am using department and year but you can use all the parameters of the QuestionDetails entity.

@Query("select qd from QuestionDetails qd where qd.department = :#{#req. department} and qd.year = :#{#req.year}")
Optional<QuestionDetails> findQuestionDetails(@Param("req") QuestionDetails req);

Ensure to implement the equals() and hashCode() in QuestionDetails class as per the unique criteria.

Your pseudo-code would look like this:

Optinal<QuestionDetails> optRecord = qdRepository.findQuestionDetails(qDetails);
if(opt.isPresent()){
return opt.get();
}else{
qdRepository.save(qDetails);
}

How to put check if record already exist - spring boot

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 Topics



Leave a reply



Submit