Jpa @OnetoOne的关系

时间:2014-03-05 11:56:46

标签: java jpa

  

这是我的实体类作者

@Entity
@Column(name = "ID")
private Long id;

@Column(name = "LAST1")
private String last;

@Column(name="FIRST1")
private String first;

@Lob
@Column(name = "BIO")
private String bio;

@OneToOne

private AuthorDetail authorId;
  getter and setters&零参数构造函数

     

这是我的另一个实体AuthorDetail,我已使用@OneToOne进行映射(可选= false,mappedBy =“authorDetail”)

 @Column(name = "ID")
private Long id;

@Column(name = "ADDRESS1")
private String address1;

@Column(name="ADDRESS2")
private String address2;

@Column(name = "CITY")
private String city;

@Column(name = "STATE1")
private String state;

@Column(name = "ZIP")
private String zip;

@Column(name = "START_DATE")
@Temporal(TemporalType.DATE)
private Date startDate;

@Lob
@Column(name = "NOTES")
private String notes;

@OneToOne(optional = false,mappedBy = "authorDetail")
private Author authorId;
  getter和setter   这是我的主要课程

`EntityTransaction entr=em.getTransaction();
        entr.begin();
        Author author=new Author();
        author.setFirst("MD");
        author.setLast("RAHMATH");
        author.setBio("A Software Developer");

        Set detailSet=new HashSet<AuthorDetail>();
        AuthorDetail detail=new AuthorDetail();
        detail.setAddress1("Address1");
        detail.setAddress2("Address2");
        detail.setCity("NoMansLand");
        detail.setState("ZZ");
        detail.setZip("12345");
        detail.setNotes("This is test detail");
        detailSet.add(detail);
        em.persist(author);
        entr.commit();`
  

如果我尝试运行程序

,我会遇到异常

2 个答案:

答案 0 :(得分:0)

如果您想要单向关系,则无需在两个类中编写@OneToOne。 从给定的代码片段来看,您似乎需要作者详细信息和作者之间的双向关系。

要让另一方知道关系(双向),需要将mappedBy属性添加到@OneToOne批注中。此属性引用作为关系所有者的实体中的(Java)属性。在您的情况下,在AuthorDetail类中,您需要添加;

@OneToOne(optional = false,mappedBy = "authorId") private Author authorId;

在mappedBy属性中,您需要引用实体而不是类名。

答案 1 :(得分:0)

Author更改以下内容:

@OneToOne
private AuthorDetail authorId;

要:

@OneToOne
private AuthorDetail authorDetail;