Reputation: 185
I Have an Entity class Certificate which has an Entity class 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;
...
}
I'm working with a legacy database. So there is no foreign key constraint even though the certificateProfileId column holds the id of the certificateProfile.
When i try to get the certificate list via CertificateDataRepository.findAll()
. I get javax.persistence.EntityNotFoundException: Unable to find CertificateProfile with id 0
I tried to set the fetchType to Lazy but I get this error:
could not initialize proxy [CertificateProfileData#1508963102] - no Session
Upvotes: 0
Views: 1586
Reputation: 469
If there is no relation(constraint) between 2 entities at the database level, you do not have to keep the mapping in the class. Remove these 2 lines:
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="certificateProfileId", foreignKey = @ForeignKey(name = "none"))
and write as follows:
@Column(name="cert_profile_id")
private Long certificateProfileId;
Upvotes: 0
Reputation: 90507
It happens in some legacy schema which do not use NULL to indicate the absent of many-to-one entities in the relationship column but instead use some magic value (which I guess in your case this magic value is 0).
By default, Hibernate throws EntityNotFoundException
if the many-to-one entities does not exist. You can use Hibernate feature @NotFound
to tell Hibernate to ignore this exception and simply assign null to the many-to-one
entities reference.
@ManyToOne
@NotFound ( action = NotFoundAction.IGNORE )
@JoinColumn(name="certificateProfileId", foreignKey = @ForeignKey(name = "none"))
private CertificateProfile certificateProfile;
Upvotes: 4