Hibernate: reuse persisted class in a persistent collection

Go To StackoverFlow.com

0

I am using hibernate and am writing code to populate an empty database. Let's pretend I'm persisting Sentences, Phrases, and Letters. Since Letters occur in both Phrases and Sentences, I'm going to have each LetterEntity have a reference to its SentenceEntity and each SentenceEntity to have a collection of letters.

@OneToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.LAZY)
@JoinColumn(name="sentenceid")
@Sort(type=SortType.NATURAL)
public SortedSet<LetterEntity> getLetters() {
    return this.letters;
}

No problem so far. Since I also want PhraseEntity to have a subcollection of letters and phrases may overlap, a Letter could be in multiple Phrases. For this I will need an additional table for the relationship.

@OneToMany(fetch = FetchType.LAZY)
@JoinTable(name = "phrase_letters", joinColumns = @JoinColumn(name = "phraseid"), inverseJoinColumns = @JoinColumn(name = "letterid"))
@Sort(type=SortType.NATURAL)
public SortedSet<TypeEntity> getLetters() {
    return this.letters;
}

When I populate the database, I just set the setSentenceId of the Letter to add it to the sentence collection. However, when I also add the Letter to the phrase using setLetters, Hibernate tries to persist the Letter again and I get an exception. How can I add the Letter to the Phrase without Hibernate trying to persist it again?

Update: I found it very helpful to read about bijective associations.

http://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/#collections-bidirectional

Although not part of my question, I had many bijective associations set up. I find them necessary in part because it makes bulk insertions much faster. When you add an element to a collection, Hibernate issues an update query.

Update: I'm an idiot. The relationship between Phrases and Letters is Many-To-Many and I was actually getting an exception because I was violating a key constraint.

2012-04-03 20:29
by schmmd


1

How are you creating your relations. The code below that seems appropriate in your case works ok.

    LetterEntity letter = new LetterEntity();
    PhraseEntity phrase = new PhraseEntity();
    SentenceEntity sentence = new SentenceEntity();

    sentence.getLetters().add(letter);
    s.persist(sentence);
    phrase.getLetters().add(letter);
    s.persist(phrase);
2012-04-03 22:10
by Piotr Kochański
So I persist the sentence, persist the letter with its sentence set to sentence, and then I add the letter to the phrase. Maybe that is the problem - schmmd 2012-04-03 22:43
Ads