-1

I have two entity classes:

User.java

Address.java

One User can have many addresses (One to Many) And Many Addresses can belong to one user (Many to One)

User.java
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
private Set<Address> userAddresses = new HashSet<Address>();

Address.java
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="UserID")
private User user;

The problem is that although the values are inserted properly in both table, the foreign key column i.e UserID is not being updated. Can anyone please suggest what is wrong with the above snippet?

Community
  • 1
  • 1
  • Show the codes that how you set the `Address` 's `user` property. – Ken Chan Jun 12 '16 at 14:57
  • @Ken Chan Hi, I got my mistake , I wasnt saving the user property in the Address. In **OneToMany** relation, the many side is the owner of the relation right ? but by specifying `mappedBy=user` we are saying that User is the owning entity. Can you please explain the above concept ? – Pooja Dubey Jun 12 '16 at 15:13
  • 1
    This link clarifies my doubt: http://stackoverflow.com/questions/2584521/in-a-bidirectional-jpa-onetomany-manytoone-association-what-is-meant-by-the-in – Pooja Dubey Jun 13 '16 at 06:06

1 Answers1

1

You are missing the targetEntity = Address.class parameter from the @OneToMany annotation. Because:

If the collection is defined using generics to specify the element type, the associated target entity type need not be specified; otherwise the target entity class must be specified. http://docs.oracle.com/javaee/5/api/javax/persistence/OneToMany.html

So it should look like this:

User.java
@OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, 
targetEntity=Address.class, mappedBy="user")
private Set<Address> userAddresses = new HashSet<Address>();

Address.java
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="UserID")
private User user;
Andras Szell
  • 527
  • 2
  • 13