繁体   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