Issue
I have two tables called Person
and Address
. These tables I mapped one to many with hibernate using annotation.
Then in my parent entity Person
I create a Set<Address>
to hold the child class. After that I create a set of address and set to Person
entity and also set Person's own values.
My problem is that when I am save the parent entity child does not save in DB.
Here is my code:
Person.java
@Entity
@Table(name="PERSON")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="personId")
private int id;
@Column(name="personName")
private String name;
@OneToMany(cascade =CascadeType.ALL,fetch = FetchType.EAGER)
@JoinColumn(name="personId")
private Set <Address> addresses;
Address.java
@Entity
@Table(name = "ADDRESS")
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "addressId")
private int id;
@Column(name = "address")
private String address;
@Column(name="personId")
private int personid;
My DAO:
public Person addNewPerson() {
Person per = new Person();
per.setName("aaaa person");
Set<Address> addressSet = new HashSet<Address>();
for(int i = 0; i<=3;i++){
Address ad = new Address();
ad.setAddress("aaa "+i);
addressSet.add(ad);
}
per.setAddresses(addressSet);
getHibernateTemplate().save(per );
}
Here person is adding in my table but address is not saved. Why?
bidirectional it is possible, but in unidirectional is my problem
Solution
The personId
column is mapped twice : once to hold the foreign key to the person of the address, using the JoinColumn
annotation, and once as a regular int
column in the address.
Remove the personId
field from the address. If you want to have the access to the person ID from the address, then map the association as a bidirectional OneToMany/ManyToOne association.
Answered By - JB Nizet
Answer Checked By - Clifford M. (JavaFixing Volunteer)