[英]hibernate one-to-one mapping, how to make two entities have same primary key
I have two entity Resource
(table resource) and VideoInfo
(table video_info), there is one-to-one unidirectional relationship from VideoInfo
to Resource
. 我有两个实体
Resource
(表资源)和VideoInfo
(表video_info),从VideoInfo
到Resource
一对一的单向关系。 The following code save one-to-one relationship but the saved column resource.id doesn't equal to video_info.resourceId. 以下代码保存了一对一关系,但保存的列resource.id不等于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?
我知道我可以手动将video_info.resourceId设置为Resource.id,是否存在任何自动方式?
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: VideoInfo实体:
@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
}
Let me answer my question: As this link @OneToOne With Shared Primary Key, Revisited say, I should use @MapsId annotation. 让我回答我的问题:再次提到带有共享主键的@OneToOne链接时,我应该使用@MapsId注释。
@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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.