I'm relatively new to Hibernate.
Question is How to fetch both child objects and parent object when parent object is fetched; however during persistence time, persist only child object.
By the by, Foreign key is NOT associated at database level.
-------------------
ParentObject.java
-------------------
private Integer internalId;
private Set<ChildObject> childObjects = new HashSet<>(0);
private Integer userId;
//associated Setters as well.
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "InternalId", unique = true, nullable = false)
public Integer getInternalId() {
return this.internalId;
}
@OneToMany(fetch = FetchType.EAGER, mappedBy = "parentObject")
public Set<ChildObject> getChildObjects() {
return childObjects;
}
-------------------
ChildObject.java
-------------------
private Integer internalRecordId;
private Integer userId;
private ParentObject parentObject;
// associated setters and remaining getters.
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "userId", nullable = true)
public ParentObject getParentObject() {
return parentObject;
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "InternalId", unique = true, nullable = false)
public Integer getInternalId() {
return this.internalId;
}
Works fine with below code
Scenario1:
Criteria criteria = getCriteria(ParentObject.java);
criteria.add(Restrictions.eq("internalId", 123);
Collection result = new LinkedHashSet(criteria.list());
List<ParentObject> resultSet = new ArrayList<>(result);
for(ParentObject parentObj : resultSet) {
parentObj.getChildObjects() --> Getting all associated Child Objects.
}
However, fails if trying to persist only child Object.
ChildObject childObj = new ChildObject();
childObj.setUserId(123456);
getSession().save(childObj);
I understand that it needs a parent object as reference, however, since business flow may not need a parent object and empty parentObject-row shouldn't persisted in DB, how this problem can be resolved?