@OneToMany关系不会将父级的主键保存在子级表中

时间:2018-10-19 07:29:25

标签: spring hibernate jpa spring-data-jpa one-to-many

让我们有三个JPA实体。一个Person和两个一对多关系。当我尝试保存Person AD_P_IDAC_P_ID外键时总是为空。 这些字段的期望值为个人ID。我在做什么错了?

  1. Person.java:它与Account和Address Entity类包含一对多关系

    @Entity
    @Table(name = "A2C_PERSON")
    class Person implements Serializable {
    
        private long id;
    
        private List<Account> acs;
    
        private List<Address> ads;
    
        @OneToMany(cascade=CascadeType.ALL, mappedBy = "person")
        public List<Account> getAccount() {
            return this.acs;
        }
    
        @OneToMany(cascade=CascadeType.ALL, mappedBy = "person")
        public List<Address> getAddress() {
            return this.ads;
        }
    }
    
  2. Account.java

    @Entity
    @Table(name = "A2C_ACCOUNT")
    public class Account implements Serializable {
    
        private long id;
    
        private Person person;
    
        @ManyToOne(cascade=CascadeType.ALL, fetch = FetchType.LAZY)
        @JoinColumn(name = "AC_P_ID")
        public Person getPerson() {
            return this.person;
        }
    }
    
  3. Address.java

    @Entity
    @Table(name = "A2C_ADDRESS")
    public class Address implements Serializable {
    
        private long id;
    
        private Person person;
    
        @ManyToOne(cascade=CascadeType.ALL,fetch = FetchType.LAZY)
        @JoinColumn(name = "AD_P_ID")
        public Person getPerson() {
            return this.person;
        }
    }
    

用于保存人员的代码:

Person p = new Person();

Account ac1 = new Account();
Account ac2 = new Account();
List<Account> acList = new ArrayList<>();
acList.add(ac1);
acList.add(ac2)

Address ad1 = new Adddress();
Address ad2 = new Adddress();
List<Address> adList = new ArrayList<>();
acList.add(ad1);
acList.add(ad2)

p.setAcs(acList);
p.setAds(adList);

personRepo.save(p);

2 个答案:

答案 0 :(得分:2)

对于每个AddressAccount实体,您需要设置Person实体。 为了使休眠状态将ID保存在子级中,这是强制性的:

Person p = new Person();

Account ac1 = new Account();
ac1.setPerson(p);  
List<Account> acList = new ArrayList<>();
acList.add(ac1);

Address ad1 = new Adddress();
ad1.setPerson(p);
List<Address> adList = new ArrayList<>();
acList.add(ad1);

答案 1 :(得分:0)

@JoinColumn表示关系的所有者。

“ MappedBy”表示反面。

所以:

@OneToMany(mappedBy = "parent")
private Collection<Child> childCollection;

不会将父级引用设置为其子级。这是你的情况。您可以按照Maciej的建议手动进行设置,但是会添加一些锅炉代码。

要自动将父级引用设置为其子级,必须通过以下方式定义关系的所有者。

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn
private Collection<Child> childCollection;