我是新来的冬眠。
我有两个类UserDetails和Address。这两者之间的关系是一对多。细节如下(跳过getter和setter)
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>();
}
地址.java
@Entity
@Table(name = "address")
public class Address {
@Id
@GeneratedValue
@Column(name = "id")
private int id;
@Column(name = "city")
private String city;
}
应用程序.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();
在 hibernate.cfg.xml 属性 name="hbm2ddl.auto" 设置为更新运行上述代码后,数据库中的条目为
用户详细信息表
userId UserName Address
1 User 1 NULL
地址表
Id City Address
1 Pune 1
2 NULL 1
我的问题是为什么休眠在地址表中插入 UserDetails Address=NULL 和 City=NULL 而不是创建新表。