我對Hibernate相對來說比較新。Hibernate JPA:如何在獲取父對象時獲取子對象;但只堅持父對象
的問題是如何當父對象是取取兩子對象和父對象;然而在持續時間期間,只能堅持子對象。
順便提一下,外鍵不在數據庫級別相關聯。
與下面的代碼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.
}
然而
-------------------
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;
}
工作正常,如果想堅持只子對象失敗。
ChildObject childObj = new ChildObject();
childObj.setUserId(123456);
getSession().save(childObj);
我明白,它需要一個父對象爲參照,但由於業務流程可能不需要父對象和空parentObject行應在DB,這個問題如何解決不持久?
謝謝你的建議! –
@SrinivasLakshman如果幫助你,請將答案標記爲「已接受」。 – yntelectual