我有两个实体Resource
(表资源)和VideoInfo
(表video_info),从VideoInfo
到Resource
存在一对一的单向关系。以下代码保存一对一关系,但保存的列resource.id不等于video_info.resourceId。注释有什么问题吗?我知道我可以手动设置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());
}
输出:
19
0
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
}
资源实体:
@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
}
答案 0 :(得分:0)
您是否尝试过@PrimaryKeyJoinColumn
注释?
像这样:
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn
private Resource resource;
关注此link以便更好地理解
答案 1 :(得分:0)
让我回答我的问题:正如此链接@OneToOne With Shared Primary Key, Revisited所说,我应该使用@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
}