Pergunta

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>
Foi útil?

Solução

The problem is that @OneToMany can only have as inverse @ManyToOne, and not @OneToOne. @OneToOne can only have as mappedBy another @OneToOne, check the javadoc for those methods.

The mapping bellow gives you the meaning you want: one user can have many addresses, but an address can only refer to only one user using the id in the foreign key specified in @JoinColumn:

@Entity
public class User {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    protected Long id;
    ...
    @OneToMany(mappedBy="user")
    private Set<Address> adresses;
} 


@Entity
public class Address {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    protected Long id;
    ...
    @ManyToOne(optional=false)
    @JoinColumn("your_foreign_key_name")
    private User user;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top