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
Generate Bank Account Number With Random
How to Check Whether an Integer Is Null or Zero in Java
How to Send Date in Rest API in Post Method
How to Convert a Kotlin Source File to a Java Source File
How to Pass List in Postman in Get Request and Get in Getmapping
Is There an Invisible Character That Is Not Regarded as Whitespace
How to Replace Multiple Words in a Single String in Java
How to Make Program to Continue Running After Exception
Jsonobject.Tostring: How Not to Escape Slashes
String Match of Only 3 Specific Words
Null Pointer on an Autowired Bean Which Is Not Mocked by Mockito
How to Get Http Response Code Using Selenium Webdriver
Convert String With Dot or Comma to Float Number
Mapstruct: Map List of Objects, When Object Is Mapped from Two Objects
How to Pass an Array to Constructor
Convert Multi If-Else to Simple Lambda Expression Code in Java