首页 > 解决方案 > JPA 与 PostgreSQL - 简单的关系

问题描述

表:

我只需要在我的 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"])]

我该怎么办?

标签: javaspringpostgresqlhibernate

解决方案


使用@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;
}

推荐阅读