我有一个有 4 个字段的表。如果我插入了一条已经存在的记录,即所有字段值都与表中的先前记录匹配。我如何只返回记录但不插入数据库?
我的模型如下所示:
@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
控制器看起来像这样:
@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;
}
使用邮递员我发送这样的数据:
{
"department" : "IT",
"year" : "2020",
"academic_year" : "1st year",
"semester" : "first semester",
"type" : "objective",
"subject" : "JAVA",
"points" : 10,
"unit" : 5
}
在这里,我正在发送表中已经存在的数据。所以,我想检查这个记录是否已经存在?如果不存在插入到表中,否则返回该存在的记录。
我如何使用 springboot Jpa hibernate 实现这一点?