【问题标题】:how to solve could not execute statement; SQL [n/a]; constraint [patient_id]; nested exception is org.hibernate.exception.ConstraintViolationException如何解决无法执行语句; SQL [不适用];约束[患者ID];嵌套异常是 org.hibernate.exception.ConstraintViolationException
【发布时间】:2019-11-15 22:17:44
【问题描述】:

我正在创建 Rest web 服务,两个实体患者和地址,在帖子中我希望将地址作为对象与患者属性一起传递,但我遇到了错误

PatientController.java

@ApiOperation(value = "Add a patient")
    @RequestMapping(value = "/patients", method= RequestMethod.POST, produces = "application/json")
    public ResponseEntity<Object> createPatient(@Valid @RequestBody Patient patient, BindingResult bindingResult) {
        if(bindingResult.hasErrors()) {
            errors = new HashMap<>();
            for(FieldError error:bindingResult.getFieldErrors()) {
                errors.put(error.getField(), error.getDefaultMessage());
            }
            return new ResponseEntity<>(errors, HttpStatus.NOT_ACCEPTABLE);
        }
        Address address = new Address();
        patient.getAddress().add(address);
        return new ResponseEntity<>(patientRepository.save(patient), HttpStatus.OK);
    }

耐心.java

@Entity
@Table(name = "patients")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"}) 
public class Patient implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "patient_id", updatable = false)
    private UUID id;
    private String name;
    private String age;
    @JsonFormat(pattern="yyyy-MM-dd")
    private Date dob;
    private String occupation;

    @Enumerated(EnumType.STRING)
    private Gender gender= Gender.MALE;

    @OneToMany(mappedBy = "patient", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<Address> address = new ArrayList<>();

    @OneToMany(mappedBy = "patient", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<Contact> contact;

    @OneToMany(mappedBy = "patient", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private List<ReferenceBy> references;

    public Patient() {}
    }

【问题讨论】:

  • 您有 2 个patient 具有相同的id

标签: java postgresql hibernate spring-boot jpa


【解决方案1】:

org.hibernate.exception.ConstraintViolationException 建议您尝试插入一条不满足您所做的约束的记录。请确保您有唯一的 id 记录和您定义为唯一的其他字段

【讨论】:

    猜你喜欢
    • 2018-07-07
    • 2019-06-06
    • 2019-11-28
    • 1970-01-01
    • 2022-11-09
    • 2020-02-12
    • 2017-01-11
    • 2019-07-24
    • 2014-03-10
    相关资源
    最近更新 更多