I am trying to establish Bidirectional Relationship between User and Address,
User 1---------->*Address
But
Address 1 -------> 1 User
On referring the internet I got these information
For one-to-one bidirectional relationships, the owning side corresponds to the side that contains the corresponding foreign key
The inverse side of a bidirectional relationship must refer to its
owning side by use of the mappedBy element of the OneToOne,
OneToMany, or ManyToMany annotation. The mappedBy element designates the property or field in the entity that is the owner of the
relationship.
But If I proceed as per information then
I need to use Mapped By on User Entity where Set <Address> hold OnetoMany mapping At the same time I need to use Mapped By on Address Entity where user holds OnetoOne mapping
Note : But @JoinColumn on Address entity for user works fine. If I use mappedBy on either User Entity or Address Entity I got the exception stating that
"The attribute [addresses] in entity class [class com.entity.User] has a mappedBy value of [User] which does not exist in its owning entity class [class com.entity.Address]. If the owning entity class is a @MappedSuperclass, this is invalid, and your attribute should reference the correct subclass."
I am confused on how to use mapped By for this type of Bi-directional relationship.
Update :
<pre>
@Entity
public class User {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
protected Long id;
...
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY,mappedBy="user")
private Set<Address> adresses;
}
@Entity
public class Address {
@Id
@GeneratedValue(strategy= GenerationType.AUTO)
protected Long id;
...
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "userid", nullable = false)
private User user;
}
</pre>