如何解决无法执行语句; SQL [n / a];约束[Patient_id];嵌套的异常是org.hibernate.exception.ConstraintViolationException

时间:2019-07-05 09:33:01

标签: java postgresql spring-boot jpa

我正在创建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);
    }

Patient.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() {}
    }

1 个答案:

答案 0 :(得分:2)

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