问题
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 HoldingPK
is 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