0

我有一个有 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 实现这一点?

4

1 回答 1

1

如下实现一个选择方法QuestionDetailsRepository。添加使记录唯一的所有条件。我使用的是部门和年份,但您可以使用QuestionDetails实体的所有参数。

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

确保按照独特的标准在课堂上实施equals()和。hashCode()QuestionDetails

您的伪代码如下所示:

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

于 2020-12-04T04:11:21.487 回答