I have two objects Mat and MatImage, parent and child resp. The primary key of MatImage is the id of Mat and they are join by one to one relationship.
If I understand bidirectional relation correctly, the child object would know about the parent if I do something like matImage.setMat(mat). I would think the primary key would be filled at this point, but it doesn't. I know this because sql throws an exception when it try to insert MatImage with #0 as matId.
Another question is with the n+1 problem. I would like to lazily load child object because not all mat has matimage. I can try changing @OneToOne to @ManyToOne but not sure how that can be done bidirectionally. Any help would be appreciated. Thank you.
Here are the entities:
// Mat
@Entity
@Table(name="mat")
public class Mat implements Serializable {
@Id
@GeneratedValue(generator="SeqMat")
@SequenceGenerator(name="SeqMat", sequenceName="seq_mat_id")
int id
@OneToOne(mappedBy="mat", optional=true, fetch=FetchType.LAZY)
@PrimaryKeyJoinColumn(name="id", referencedColumnName="matId")
@Cascade([ALL, DELETE_ORPHAN])
MatImage matImage
int matTemplateId
int number
...
}
// MatImage
@Entity
@Table(name="matimage")
public class MatImage implements Serializable {
@Id
int matId
@OneToOne(optional=true, fetch=FetchType.LAZY)
@JoinColumn(name="matId", referencedColumnName="id")
Mat mat
@Column(name="img_eventid")
int eventId
...
}