one to many unidirectional hibernate mapping doesn't save the child table

∥☆過路亽.° 提交于 2019-12-23 17:45:03

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/7819389/one-to-many-unidirectional-hibernate-mapping-doesnt-save-the-child-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!