0

我有一个实体类证书,它有一个实体类 CertificateProfile。

public class Certificate {
    @Id
    private String certId;

    @ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name="certificateProfileId", foreignKey = @ForeignKey(name = "none"))
    private CertificateProfile certificateProfile;
}

public class CertificateProfile {
    @Id
    private Long id;

    private String certificateProfileName;
...
}

我正在使用旧数据库。因此,即使 certificateProfileId 列包含 certificateProfile 的 id,也没有外键约束。当我尝试通过CertificateDataRepository.findAll(). 我得到javax.persistence.EntityNotFoundException: Unable to find CertificateProfile with id 0 我试图将 fetchType 设置为 Lazy 但我收到此错误:

could not initialize proxy [CertificateProfileData#1508963102] - no Session
4

2 回答 2

2

它发生在一些不使用 NULL 表示关系列中不存在多对一实体而是使用一些魔法值(我猜在你的情况下这个魔法值是 0)的遗留模式中。

默认情况下,EntityNotFoundException如果多对一实体不存在,Hibernate 会抛出异常。您可以使用 Hibernate 功能@NotFound告诉 Hibernate 忽略此异常并简单地将 null 分配给many-to-one实体引用。

    @ManyToOne
    @NotFound ( action = NotFoundAction.IGNORE )
    @JoinColumn(name="certificateProfileId", foreignKey = @ForeignKey(name = "none"))
    private CertificateProfile certificateProfile;
于 2020-05-19T20:49:34.677 回答
0

如果数据库级别的 2 个实体之间没有关系(约束),则不必将映射保留在类中。删除这两行:

@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="certificateProfileId", foreignKey = @ForeignKey(name = "none"))

并写如下:

@Column(name="cert_profile_id")
private Long certificateProfileId;
于 2020-05-19T23:41:26.947 回答