I have two entity Resource
(table resource) and VideoInfo
(table video_info), there is one-to-one unidirectional relationship from VideoInfo
to Resource
. The following code save one-to-one relationship but the saved column resource.id doesn't equal to video_info.resourceId. Is there anything wrong with the annotations? I know I can manually set video_info.resourceId equal to Resource.id, does any automatic way exist?
public static void main(String[] args) throws IOException {
Resource r=new Resource();
r.setName("test");
r.setPath("foo");
r.setType("video");
VideoInfo videoInfo=new VideoInfo();
videoInfo.setResource(r);
Session session=Database.getSessionFactory().openSession();
Transaction transaction=session.beginTransaction();
try {
session.save(videoInfo);
transaction.commit();
}catch (Exception e){
transaction.rollback();
return;
}
System.out.println(r.getId());
System.out.println(videoInfo.getResourceId());
}
output:
19
0
VideoInfo entity:
@Entity
@Table(name = "video_info")
public class VideoInfo {
@Id
private int resourceId;
@Column(name = "type")
private String type;
@Column(name = "time")
private Integer time;
@Column(name = "actors")
private String actors;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "resourceId")
private Resource resource;
//getters and setters
}
Resource entity:
@Entity
@Table(name = "resource")
public class Resource {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
@Column(name = "name")
private String name;
@Column(name = "path")
private String path;
@Column(name = "type")
private String type;
//getters and setters
}
Have you tried @PrimaryKeyJoinColumn
annotation ?
Like this:
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn
private Resource resource;
Follow this link for better understanding
Let me answer my question: As this link @OneToOne With Shared Primary Key, Revisited say, I should use @MapsId annotation.
@Entity
@Table(name = "video_info")
public class VideoInfo {
@Id
private int resourceId;
@Column(name = "type")
private String type;
@Column(name = "time")
private Integer time;
@Column(name = "actors")
private String actors;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "resourceId")
@MapsId
private Resource resource;
//getters and setters
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.