I have a table with 4 fields. And if i inserted a record that already exists i.e all field value matches with previous record in table. How do i return record only but not insert into database ?
My model look like this:
@Entity
public class QuestionDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String department;
private String year;
private String academic_year;
private String semester;
private String type;
private String subject;
private int points;
private int unit;
// getter, setter
And Controller look this:
@Autowired
public QuestionDetailsRepository qdRepository;
@PostMapping("/api/questionDetails")
public QuestionDetails addQuestion(@Valid @RequestBody QuestionDetails qDetails) {
// here i want to first check if qDetails object is already present in table .
If present i want to return that existed record instead of inserting into table.
QuestionDetails qd = qdRepository.save(qDetails); // save only new record
return qd;
}
Using postman i send data like this:
{
"department" : "IT",
"year" : "2020",
"academic_year" : "1st year",
"semester" : "first semester",
"type" : "objective",
"subject" : "JAVA",
"points" : 10,
"unit" : 5
}
Here, i am sending data that is already present in table. So, i want to check if this record already exist? If doesn't exist insert into table otherwise return that existed record.
How do i achieve that using springboot Jpa hibernate?
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);
}