一对多单向休眠映射不保存子表 [英] one to many unidirectional hibernate mapping doesn't save the child table
问题描述
我有两个表,分别称为 Person
和 Address
.我使用注释将这些表映射到一对多.
I have two tables called Person
and Address
. These tables I mapped one to many with hibernate using annotation.
然后在我的父实体 Person
中创建一个 Set
来保存子类.之后,我创建了一组地址并设置为 Person
实体并设置 Person 自己的值.
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.
这是我的代码:
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;
我的 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
推荐答案
personId
列被映射两次:一次是保存地址的人的外键,使用 JoinColumn
注释,并作为地址中的常规 int
列一次.
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.
从地址中删除 personId
字段.如果您想从地址访问人员 ID,则将该关联映射为双向 OneToMany/ManyToOne 关联.
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.
这篇关于一对多单向休眠映射不保存子表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!