2014-03-05 46 views
0

这是我的实体类作者JPA @OneToOne关系

@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和setter &零参数的构造函数

,这是我的其他实体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();` 

我得到异常,如果我尝试如果你想有一个单向关系运行程序

+0

您使用的是detailSet什么设置?你不应该使用新的细节设置作者的authId吗?请同时发布你得到的例外,因为他们帮助指出问题 – Chris

回答

0

,你不需要在这两门课都写@OneToOne。 从给定的代码片段看来,您希望Author细节和Author之间的双向关系。

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

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

在mappedBy属性,你需要给参考实体不类名。

+0

作者author = new Author(); author.setFirst(“MD”); author.setLast(“RAHMATH”); author.setBio(“软件开发人员”); //设置 detailSet; // detailSet = new HashSet (); 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”); detail.setAuthorId(作者);如何设置authorId的值 – user3227175

0

在你Author变化如下:

@OneToOne 
private AuthorDetail authorId; 

要:

@OneToOne 
private AuthorDetail authorDetail;