I have an entity that looks like this
@Entity
@IdClass(AId.class)
class A {
@Id
private String userName
@Id
@NotNull
@JoinColumn(name = "location_id", referenceColumnName = "id", nullable=false, foreignKey = @ForeignKey(name = ...))
private Location location;
private String userInformation;
}
The class Location looks like this:
@Entity
class Location {
@NotNull
private Long id;
@NotNull
@Column(nullable = false}
private String name;
}
And then I have a class to define the Id
class AId implements Serializable {
private Long locationId;
private String userName;
}
Now, I do some manipulation on the object of class A and then want to store it. However, I get an exception that tells me that the non-nullable field Location#name that is reference by an object of A is null. I debugged through it and made sure that the field is actually not null. However, I still get this. What’s the issue? The location that A is referring to is already persisted on the database.
2
Answers
This may be caused by the types of @Id fields not matching the types in id class. According to https://docs.oracle.com/javaee/7/api/javax/persistence/IdClass.html
Try with ManyToOne and change locationId to location :
See also https://jakartaee.github.io/jakartaee-documentation/jakartaee-tutorial/9.1/persist/persistence-basicexamples/persistence-basicexamples.html