Ein Zu Viele und Doppelte Eintrag

Verwende ich JPA->Hibernate. PlayFramework. Ich will eine Beziehung zu haben.

 Category - 1:n -> Tag

Jede Kategorie kann beliebig viele tags, aber tags nicht zu kennen.

So, ich mag das:

@Entity
public class Category ... {
    @OneToMany
    public List<Tag> tags = new LinkedList<Tag>();
}

Habe ich test:

@Test
public void playWithTags() {

    Tag tag1 = new Tag("tag1").save(); //managed by playframework

    Category cat1 = new Category("cat1");
    cat1.tags.add(tag1);
    cat1.save();

    //check if tag1 and cat1 were saved  
    assertEquals(1, Tag.count());
    assertEquals(1, Category.count());

    Category cat2 = new Category("cat2");
    cat2.tags.add(tag1);
    cat2.save();

}

Ist das Ergebnis:

16:18:01,555 ERROR ~ Duplicate entry '1' for key 'tags_id'
16:18:01,555 ERROR ~ Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:96)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelp
....
java:908)
    at java.lang.Thread.run(Thread.java:619)
Caused by: java.sql.BatchUpdateException: Duplicate entry '1' for key 'tags_id'
    at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2020)

Scheint es, dass cat2.save() versuchen, mehr zu tun, dann sollte es

Falls, wenn die Verwendung der merge() anstelle von save() funktioniert es gut:

 cat2.merge();

ABER WARUM?

InformationsquelleAutor ses | 2011-04-29
Schreibe einen Kommentar