开发者

Saving owned/child objects in Hibernate

开发者 https://www.devze.com 2023-01-03 23:11 出处:网络
I\'m having a hard time wrapping my head around the way hibernate objects work. Here\'s a little chunk of what my model looks like:

I'm having a hard time wrapping my head around the way hibernate objects work. Here's a little chunk of what my model looks like:

JobOpening:

@ManyToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL)
@JoinTable(
        name="jobOpening_questionSet",
        joinColumns=@JoinColumn(name="jobOpenings_id"),
        inverseJoinColumns=@JoinColumn(name="questionSets_id")
)
@IndexColumn(name="question_sets_idx",base=0,nullable=false)
public List<QuestionSet> getQuestionSets() {
    return questionSets;
}

QuestionSet:

@ManyToMany(mappedBy="questionSets",fetch=开发者_如何学CFetchType.EAGER)
public Set<JobOpening> getJobOpenings() {
    return jobOpenings;
}

@OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER)
@IndexColumn(name="questions_idx",base=0)
@JoinColumn(name="questionset_id",nullable=false)
public List<FormQuestion> getQuestions() {
    return questions;
}

FormQuestion:

@ManyToOne
@JoinColumn(name="questionset_id", insertable=false, updatable=false, nullable=false)
@OnDelete(action=OnDeleteAction.CASCADE)
public QuestionSet getQuestionSet() {
    return questionSet;
}

Now how would I go about, say, modifying a question in the question set, or changing which jobs a questionset is associated with? For example, to edit a question in a questionset, I imagine I should be able to just get the question via its id, change some values, and merge() it back in, but this doesn't work.

I'm using Hibernate from Spring (appfuse), usually as detached objects.


The hibernate session works in a slightly different way:

  • the SessionFactory creates a Session. Most often a new Session is created for each thread. This is called session-per-request in a web-context.
  • Hibernate objects (entities) have three states - persistent, detached and transient:

    • persistent means that the object has recently been loaded by the currently active session
    • transient means that the object has never been part of the session
    • detached means that the object has once been loaded of the session, but the session has been closed (and it is not detached from the session it was associated with)
  • persistent objects need not be merged, updated or anything - whenever you change their internal state, hibernate already knows that, and it creates the necessary queries on the next flush()

  • detached objects need to be merged back into the session, but their identity must be recognizable - by overriding hashCode() and equals() with a business key.

Take a look at Sessions and transactions documentation

0

精彩评论

暂无评论...
验证码 换一张
取 消