views:

44

answers:

1

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=FetchType.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.

A: 

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

Bozho
I guess my question then would be, if I modify a detached object by adding to its list of children (or parents), and then I merge it into a session, what happens? Does the child/parent's list of parents/children get automatically updated? or do I have to go through them all and fix them manually?
maxdj
yes, if `cascade` includes `MERGE`
Bozho