简体   繁体   中英

Jpa @OnetoOne relationship

This is my entity class Author

@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;

getters and setters & zero parameter constructor

this is my other entity AuthorDetail here i have mapped using @OneToOne(optional = 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;

getters and setters this my main class

`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();`

i am getting exceptions if i try run the program

If you want a single-directional relation, you don't need to write @OneToOne in both class. From the given piece of code, it appears that you want the bi-direction relationship between Author detail and Author.

For the other side to be aware of the relation (bidirectional), it is required to add the mappedBy attribute to the @OneToOne annotation. This attribute references the (Java) property in the entity that is the owner of the relationship. In your case, in AuthorDetail class you need to add;

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

In mappedBy property, you need to give reference to the entity not class name.

In your Author change the following:

@OneToOne
private AuthorDetail authorId;

To:

@OneToOne
private AuthorDetail authorDetail;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM