简体   繁体   English

Jpa @OnetoOne关系

[英]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 getter和setter和零参数构造函数

this is my other entity AuthorDetail here i have mapped using @OneToOne(optional = false,mappedBy = "authorDetail") 这是我的另一个实体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;

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. 如果需要单向关系,则无需在两个类中都编写@OneToOne。 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. 为了让另一端了解该关系(双向),需要将mapledBy属性添加到@OneToOne批注中。 This attribute references the (Java) property in the entity that is the owner of the relationship. 此属性引用作为关系所有者的实体中的(Java)属性。 In your case, in AuthorDetail class you need to add; 您需要在AuthorDetail类中添加;

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

In mappedBy property, you need to give reference to the entity not class name. 在mappedBy属性中,您需要引用实体而不是类名。

In your Author change the following: 在您的Author更改以下内容:

@OneToOne
private AuthorDetail authorId;

To: 至:

@OneToOne
private AuthorDetail authorDetail;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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