2010-08-29 6 views
4

Je reçois la trace de pile ci-dessous, bien que les données soient insérées avec succès.org.hibernate.exception.ConstraintViolationException: impossible d'exécuter la mise à jour par lots JDBC

Hibernate: select attendee_.attendeeId, attendee_.attendeeName as attendee2_1_ from attendee attendee_ where attendee_.attendeeId=? 
Hibernate: select attendee_.attendeeId, attendee_.attendeeName as attendee2_1_ from attendee attendee_ where attendee_.attendeeId=? 
Hibernate: insert into event (eventName, startDate, eventId) values (?, ?, ?) 
Hibernate: insert into attendee (attendeeName, attendeeId) values (?, ?) 
Hibernate: insert into attendee (attendeeName, attendeeId) values (?, ?) 
Hibernate: update attendee set attendeeId=? where attendeeId=? 
Hibernate: update attendee set attendeeId=? where attendeeId=? 
Aug 29, 2010 7:39:10 PM org.hibernate.util.JDBCExceptionReporter logExceptions 
WARNING: SQL Error: 1062, SQLState: 23000 
Aug 29, 2010 7:39:10 PM org.hibernate.util.JDBCExceptionReporter logExceptions 
SEVERE: Duplicate entry '11' for key 'PRIMARY' 
Aug 29, 2010 7:39:10 PM org.hibernate.event.def.AbstractFlushingEventListener performExecutions 
SEVERE: 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:69) 
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) 
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:202) 
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:230) 
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:144) 
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:296) 
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27) 
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:980) 
    at com.practice.hibernate.basic.BasicOperations.main(BasicOperations.java:51) 
Caused by: java.sql.BatchUpdateException: Duplicate entry '11' for key 'PRIMARY' 
    at com.mysql.jdbc.ServerPreparedStatement.executeBatch(ServerPreparedStatement.java:665) 
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:58) 
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:195) 
    ... 6 more 
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update 
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:69) 
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43) 
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:202) 
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:230) 
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:144) 
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:296) 
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27) 
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:980) 
    at com.practice.hibernate.basic.BasicOperations.main(BasicOperations.java:51) 
Caused by: java.sql.BatchUpdateException: Duplicate entry '11' for key 'PRIMARY' 
    at com.mysql.jdbc.ServerPreparedStatement.executeBatch(ServerPreparedStatement.java:665) 
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:58) 
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:195) 
    ... 6 more 

S'il vous plaît noter:

a) Ma db n'a aucun enregistrement actuellement b) Les données s'inséré dans DB avec succès.

Ici j'essaye de persister un objet d'événement qui contient deux objets de participant. C'est tout.

Mon test Classe:

public static void main(String[] args) { 
    Session session = HibernateRuntime.getSession(); 

    try { 
     Set<Attendee> attendees = new HashSet<Attendee>(2); 

     Attendee attendee = new Attendee(); 
     attendee.setAttendeeId(3); 
     attendee.setAttendeeName("Baswanth Rao"); 

     Attendee attendee1 = new Attendee(); 
     attendee1.setAttendeeId(4); 
     attendee1.setAttendeeName("Razi Ahmed"); 

     attendees.add(attendee); 
     attendees.add(attendee1); 

     Event event = new Event(); 
     event.setEventId(11); 
     event.setEventName("Initiatives Workshop 3"); 
     event.setStartDate(new Date()); 
     event.setAttendees(attendees); 

     session.save(event); 
     session.flush(); 

    } finally { 
     session.close(); 
    } 
} 

Event.hbm.xml:

<hibernate-mapping package="com.practice.hibernate.vo"> 
    <class name="Event" table="event"> 
     <id name="eventId" column="eventId" type="long"> 
      <generator class="assigned" /> 
     </id> 

     <property name="eventName" type="string" length="100" /> 
     <property name="startDate" type="date" /> 

     <set name="attendees" cascade="all"> 
      <key column="attendeeId" /> 
      <one-to-many class="Attendee" /> 
     </set> 
    </class> 
</hibernate-mapping> 

hibernate.cfg.xml

<hibernate-configuration> 
    <session-factory> 
     <property name="connection.driver_class">com.mysql.jdbc.Driver</property> 
     <property name="connection.url">jdbc:mysql://localhost/test</property> 
     <property name="connection.username">root</property> 
     <property name="connection.password"></property> 
     <property name="connection.autocommit">false</property> 

     <property name="dialect">org.hibernate.dialect.MySQLDialect</property> 
     <property name="show_sql">true</property> 

     <mapping resource="com/practice/hibernate/vo/Event.hbm.xml"></mapping> 
     <mapping resource="com/practice/hibernate/vo/Attendee.hbm.xml"></mapping> 
    </session-factory> 
</hibernate-configuration> 
+0

supprimer la dépendance à ATTENDEE et essayer à nouveau. ou vérifiez votre Attendee.hbm.xml – mhshams

+0

êtes-vous sûr que le code de test s'exécute seulement 1 fois? vous pouvez mettre un peu de journal dans votre méthode principale pour vous assurer qu'il est juste exécuté. – mhshams

+0

Bashu, utilisez le lien "modifier" pour ajouter ceci à la question.Il est en bas à gauche du texte de votre question, juste en dessous du bouton pour le tag hibernate. – meriton

Répondre

11

Votre Même t.hbm.xml dit:

<set name="attendees" cascade="all"> 
    <key column="attendeeId" /> 
    <one-to-many class="Attendee" /> 
</set> 

cela signifie plaine en anglais, que la colonne Attendee.attendeeId est la clé étrangère pour l'association attendees et des points à la clé primaire de Event. Lorsque vous ajoutez ces Participants à l'événement, Hibernate met à jour la clé étrangère pour exprimer l'association modifiée. Puisque cette même colonne est également la clé primaire de Attendee, cela viole la contrainte de clé primaire.

Étant donné que l'identité d'un Participant et la participation à un événement sont indépendantes, vous devez utiliser des colonnes distinctes pour les clés principale et étrangère. Editer: Les sélections peuvent être parce que vous ne semblez pas avoir une propriété de version configurée, ce qui empêche Hibernate de savoir si les participants existent déjà dans la base de données (ils ont peut-être été chargés dans une session précédente), donc hibernate émet des sélections à vérifier. En ce qui concerne les instructions de mise à jour, il était probablement plus facile à mettre en œuvre de cette façon. Si vous voulez vous débarrasser de ces mises à jour séparées, je recommande de mapper l'association à partir des deux extrémités, et déclarez Event -end comme inverse.

+0

ouais, c'est le problème, vous devriez avoir une autre colonne dans votre table des participants – mhshams

+0

Ouais ... merci Meriton. Les problèmes sont résolus maintenant ... Je suis désolé c'était un problème de base, je devrais avoir vérifié à fond peut être. – Bashu

+0

Pourriez-vous également expliquer pourquoi les 2 premières sélections et les 2 dernières mises à jour sont exécutées. Impossible d'éviter ces deux instructions de mise à jour? – Bashu

-2

Vous devrez peut-être gérer javax.persistence.RollbackException

Questions connexes