I am new to hibernate.
I have two classes UserDetails and Address.The relation between these two is One-To-Many.The details are as follows(Skiping getter and setters)
UserDetails.java
@Entity
@Table(name = "UserDetails")
public class UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "userId")
private int userId;
@Column(name = "UserName")
private String userName;
@OneToMany
@JoinColumn(name = "address")
private Collection<Address> address = new ArrayList<Address>();
}
Address.java
@Entity
@Table(name = "address")
public class Address {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "city")
private String city;
}
App.java
UserDetails ud=new UserDetails();
ud.setUserName("User 1");
Address ad1=new Address();
ad1.setCity("Mumbai");
Address ad2=new Address();
ad1.setCity("Pune");
ud.getAddress().add(ad1);
ud.getAddress().add(ad2);
Session session=factory.openSession();
session.beginTransaction();
session.save(ud);
session.save(ad1);
session.save(ad2);
session.getTransaction().commit();
session.close();
In hibernate.cfg.xml property name="hbm2ddl.auto" is set to update After Running above code the entry in database is
UserDetails Table
userId UserName Address
1 User 1 NULL
Address Table
Id City Address
1 Pune 1
2 NULL 1
My Question is why hibernate is inserting in UserDetails Address=NULL and City=NULL in address table instead of creating new table.
Address ad2=new Address();
ad1.setCity("Pune");
You are setting the city pune
to address1
,instead of address2
try changing it as
Address ad2=new Address();
ad2.setCity("Pune");
UPDATE
Your user table adrees column is null because there is no mapped field in your pojo for address anyways your way of database schema design is wrong implementing onetomany relationship. Please check here One to Many Hibernate for proper way