Himanshu Yadav
Himanshu Yadav

Reputation: 13587

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

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.

Upvotes: 2

Views: 1729

Answers (1)

JB Nizet
JB Nizet

Reputation: 691625

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.

Upvotes: 2

Related Questions