簡體   English   中英

休眠一對一映射,如何使兩個實體具有相同的主鍵

[英]hibernate one-to-one mapping, how to make two entities have same primary key

我有兩個實體Resource (表資源)和VideoInfo (表video_info),從VideoInfoResource一對一的單向關系。 以下代碼保存了一對一關系,但保存的列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
}

您是否嘗試過@PrimaryKeyJoinColumn注解?

像這樣:

@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn
private Resource resource;

點擊此鏈接可更好地了解

讓我回答我的問題:再次提到帶有共享主鍵的@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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM