2014-03-05 154 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;