Hibernate Mapping One To Many Relationship:Parent's PK to Child's FK

好久不见. 提交于 2020-01-24 13:24:21

问题


I have a classic one to many relationship and while saving it with Hibernate, I am not able to pass parent's PK column value to Child's FK column.
Parent Class

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int holdingPK;

@OneToMany(mappedBy="holding",targetEntity=PolicyType.class,fetch=FetchType.LAZY, cascade = CascadeType.ALL)
@XmlElement(name = "Policy")
private Set<PolicyType> policy;

Child Class

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int policyPK;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="HoldingFK",nullable = false)
private HoldingType holding;

Here HoldingPKis a auto generated sequence column which represents primary key. Value gets generated when I insert a Holding row. So I want to pass HoldingPK value to child's HoldingFK column on the fly.
Test Code

HoldingType obj = new HoldingType();
obj.setCurrencyTypeCode("6");
obj.setHoldingKey("123");
Set<PolicyType> set = new TreeSet<PolicyType>();
PolicyType policy = new PolicyType();
policy.setJurisdiction("Haha");
set.add(policy);
obj.setPolicy(set);
session.save(obj);
transaction.commit();

So I am able to pass Child's other values to Child Table column, just Parent PK is not reaching to Child's FK column.

Here I am persisting XML document values to database. For this I am marshalling XML to Java Objects using JAXB then persisting objects using Hibernate. In this way I am reusing JAXB generated classes with Hibernate and these PK and FK elements do not exist on XML. These are specific to Database.


回答1:


You simply forgot to initialise the owning side of the bidirectional association. You only initialized the inverse side (the one which has the mappedBy attribute). Hibernate only considers the owning side to know if an association exists or not (the side without the mappedBy attribute).

Add this to your code (before the holding is saved):

policy.setHolding(obj);

Side note: your code would be much more readable if you named the policy field (and accessors) policies. There are many of them, so it should have a plural form.



来源:https://stackoverflow.com/questions/11452388/hibernate-mapping-one-to-many-relationshipparents-pk-to-childs-fk

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