一对多的单向Hibernate映射不救子表

一对多的单向Hibernate映射不救子表

本文介绍了一对多的单向Hibernate映射不救子表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表名为地址。这些表映射到我的一对多的使用注释休眠。

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.

我的问题是,当我保存父实体孩子DB不保存。

My problem is that when I am save the parent entity child does not save in DB.

下面是我的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;

我的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,然后映射协会作为一个双向的一对多/多对一关联。

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.

这篇关于一对多的单向Hibernate映射不救子表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 03:58