JPA 与 PostgreSQL - 简单关系

表格:

  • 患者 ( id, 姓名, id_status, ...) -> FK 到 pattient_status

  • pattient_status (id, 描述) -> 目标表

我需要的只是在 pattient.class 中获取 pattient_status.description,因为我的 GET 方法需要 JSON 返回上的此信息。

代码:

@Entity

@Table(name="cad_paciente")

public class Paciente {


... (other columns)


@OneToOne

    @JoinColumn(insertable=false, updatable=false, name = "id_status_paciente", referencedColumnName = "id")

    private StatusPaciente status;


public String getStatusPaciente(){

        return status.getStatus();

    }


----

@Entity

@Table(name="cad_status_paciente")

public class StatusPaciente {


    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;


    @Column(name="ds_status")

    @Size(max=50)

    private String status;

这正确列出了我的信息,但在 POST 方法上,JPA 正确保存但返回消息:


Resolved [org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: (was java.lang.NullPointerException); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: com.spin.spincare.model.Paciente["statusPaciente"])]

我应该怎么办?


阿波罗的战车
浏览 134回答 2
2回答

达令说

这是你的吸气剂的问题:public String getStatusPaciente() {    return status.getStatus();}在您的 POST 调用中,状态为 null,因此当 Jackson 使用此 getter 生成 JSON 时,它会出现空指针异常。将其更新为:public String getStatusPaciente() {    if (status == null) {        return null;    }    return status.getStatus();}

暮色呼如

使用@MapsId. 这将使实体的 id 匹配。@Entity@Table(name="cad_status_paciente")public class StatusPaciente {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    private Long id;    @MapsId    @OneToOne    private Paciente paciente;    @Column(name="ds_status")    @Size(max=50)    private String status;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java