Hibernate Дублирующая запись '1' для ключа 'PRIMARY' при первой вставке в таблицу - PullRequest
5 голосов
/ 27 апреля 2011

Я получаю сообщение об ошибке Дублирующая запись '1' для ключа 'PRIMARY', когда я впервые вставляю в таблицу (после удаления / создания моей базы данных).Это вызывает откат.Если я выполню снова, строки будут вставлены ОК.Может кто-нибудь объяснить мне, почему / что я делаю неправильно?

У меня есть пользовательский класс (предварительно заполненный в БД), к которому прикреплен список задач.В базе данных есть таблицы users, user-tasks и tasks

User.hbm содержит

<id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="increment" />
        </id>
<list name="tasks" cascade="all" table="user_tasks" lazy="false">
            <key column="user_id"/>
            <index column="id"/>
            <many-to-many column="task_id" class="com.some.package.classes.Task"/>
        </list>`

Task.hbm содержит

<id name="id" type="java.lang.Integer">
        <column name="id" />
        <generator class="increment" />
    </id>
<list name="users" cascade="all" table="user_tasks" lazy="false"
    inverse="false">
        <key column="task_id"/>
        <index column="id"/>
        <many-to-many column="user_id" class="com.some.packageclasses.User"/>
    </list>

Показываются 2 журнала (дляне работает, а затем работает)

r:1112 - Inserting collection: [com.some.package.classes.User.tasks#1]
14:39:16,488 DEBUG AbstractBatcher:410 - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
14:39:16,489 DEBUG SQL:111 - insert into user_tasks (user_id, id, task_id) values (?, ?, ?)    
14:39:16,489 TRACE AbstractBatcher:513 - preparing statement
14:39:16,489 TRACE IntegerType:151 - binding '1' to parameter: 1
14:39:16,489 TRACE IntegerType:151 - binding '0' to parameter: 2
14:39:16,490 TRACE IntegerType:151 - binding '1' to parameter: 3
14:39:16,490 DEBUG AbstractBatcher:248 - reusing prepared statement
14:39:16,490 DEBUG SQL:111 - insert into user_tasks (user_id, id, task_id) values (?, ?, ?)
14:39:16,490 TRACE IntegerType:151 - binding '1' to parameter: 1
14:39:16,490 TRACE IntegerType:151 - binding '1' to parameter: 2
14:39:16,490 TRACE IntegerType:151 - binding '2' to parameter: 3
14:39:16,490 DEBUG AbstractBatcher:248 - reusing prepared statement
14:39:16,490 DEBUG SQL:111 - insert into user_tasks (user_id, id, task_id) values (?, ?, ?)
14:39:16,490 TRACE IntegerType:151 - binding '1' to parameter: 1
14:39:16,491 TRACE IntegerType:151 - binding '2' to parameter: 2
14:39:16,491 TRACE IntegerType:151 - binding '3' to parameter: 3
14:39:16,491 DEBUG AbstractBatcher:248 - reusing prepared statement
14:39:16,491 DEBUG SQL:111 - insert into user_tasks (user_id, id, task_id) values (?, ?, ?)
14:39:16,491 TRACE IntegerType:151 - binding '1' to parameter: 1
14:39:16,491 TRACE IntegerType:151 - binding '3' to parameter: 2
14:39:16,491 TRACE IntegerType:151 - binding '4' to parameter: 3
14:39:16,491 DEBUG AbstractBatcher:248 - reusing prepared statement
14:39:16,491 DEBUG SQL:111 - insert into user_tasks (user_id, id, task_id) values (?, ?, ?)
14:39:16,492 TRACE IntegerType:151 - binding '1' to parameter: 1
14:39:16,492 TRACE IntegerType:151 - binding '4' to parameter: 2
14:39:16,492 TRACE IntegerType:151 - binding '5' to parameter: 3
14:39:16,492 DEBUG AbstractCollectionPersister:1194 - done inserting collection: 5 rows inserted
14:39:16,493 DEBUG AbstractBatcher:66 - Executing batch size: 5
14:39:16,510 DEBUG AbstractBatcher:418 - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
14:39:16,511 TRACE AbstractBatcher:562 - closing statement
14:39:16,515 DEBUG JDBCExceptionReporter:92 - Could not execute JDBC batch update [insert into user_tasks (user_id, id, task_id) values (?, ?, ?)]
java.sql.BatchUpdateException: Duplicate entry '1' for key 'PRIMARY'
    at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2024)
    at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1449)
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:171)
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1028)
    at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:366)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
    at com.some.package.TimeMgmt.submitTasks(TimeMgmt.java:165)
    at com.some.package.TimeMgmt.main(TimeMgmt.java:228)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'PRIMARY'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
    at com.mysql.jdbc.Util.getInstance(Util.java:382)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1039)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3603)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3535)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1989)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2150)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2626)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415)
    at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1976)
    ... 12 more
14:39:16,518  WARN JDBCExceptionReporter:100 - SQL Error: 1062, SQLState: 23000
14:39:16,518 ERROR JDBCExceptionReporter:101 - Duplicate entry '1' for key 'PRIMARY'
14:39:16,519 ERROR AbstractFlushingEventListener:324 - 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:94)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:171)
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1028)
    at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:366)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
    at com.some.package.TimeMgmt.submitTasks(TimeMgmt.java:165)
    at com.some.package.TimeMgmt.main(TimeMgmt.java:228)
Caused by: java.sql.BatchUpdateException: Duplicate entry '1' for key 'PRIMARY'
    at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2024)
    at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1449)
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
    ... 9 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'PRIMARY'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
    at com.mysql.jdbc.Util.getInstance(Util.java:382)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1039)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3603)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3535)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1989)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2150)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2626)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415)
    at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1976)
    ... 12 more
14:39:16,519 TRACE ConnectionManager:501 - registering flush end
14:39:16,519 DEBUG JDBCTransaction:186 - rollback
14:39:16,521 DEBUG JDBCTransaction:197 - rolled back JDBC Connection
14:39:16,522 TRACE JDBCContext:242 - after transaction completion
14:39:16,522 DEBUG ConnectionManager:427 - aggressively releasing JDBC connection
14:39:16,522 DEBUG ConnectionManager:464 - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
14:39:16,522 TRACE DriverManagerConnectionProvider:152 - returning connection to pool, pool size: 1
14:39:16,522 TRACE SessionImpl:450 - after transaction completion
14:39:16,525 TRACE SessionImpl:301 - closing session
14:39:16,526 TRACE ConnectionManager:398 - connection already null in cleanup : no action
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266)
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:171)
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1028)
    at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:366)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
    at com.some.package.TimeMgmt.submitTasks(TimeMgmt.java:165)
    at com.some.package.TimeMgmt.main(TimeMgmt.java:228)
Caused by: java.sql.BatchUpdateException: Duplicate entry '1' for key 'PRIMARY'
    at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:2024)
    at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1449)
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
    ... 9 more
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'PRIMARY'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
    at com.mysql.jdbc.Util.getInstance(Util.java:382)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1039)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3603)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3535)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1989)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2150)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2626)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119)
    at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2415)
    at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1976)
    ... 12 more



>14:39:40,542 DEBUG AbstractCollectionPersister:1112 - Inserting collection: [com.some.package.classes.User.tasks#1]
14:39:40,542 DEBUG AbstractBatcher:410 - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
14:39:40,543 DEBUG SQL:111 - insert into user_tasks (user_id, id, task_id) values (?, ?, ?)
14:39:40,543 TRACE AbstractBatcher:513 - preparing statement
14:39:40,544 TRACE IntegerType:151 - binding '1' to parameter: 1
14:39:40,544 TRACE IntegerType:151 - binding '0' to parameter: 2
14:39:40,544 TRACE IntegerType:151 - binding '1' to parameter: 3
14:39:40,544 DEBUG AbstractBatcher:248 - reusing prepared statement
14:39:40,544 DEBUG SQL:111 - insert into user_tasks (user_id, id, task_id) values (?, ?, ?)
14:39:40,544 TRACE IntegerType:151 - binding '1' to parameter: 1
14:39:40,545 TRACE IntegerType:151 - binding '1' to parameter: 2
14:39:40,545 TRACE IntegerType:151 - binding '2' to parameter: 3
14:39:40,545 DEBUG AbstractBatcher:248 - reusing prepared statement
14:39:40,545 DEBUG SQL:111 - insert into user_tasks (user_id, id, task_id) values (?, ?, ?)
14:39:40,545 TRACE IntegerType:151 - binding '1' to parameter: 1
14:39:40,545 TRACE IntegerType:151 - binding '2' to parameter: 2
14:39:40,546 TRACE IntegerType:151 - binding '3' to parameter: 3
14:39:40,546 DEBUG AbstractBatcher:248 - reusing prepared statement
14:39:40,546 DEBUG SQL:111 - insert into user_tasks (user_id, id, task_id) values (?, ?, ?)
14:39:40,546 TRACE IntegerType:151 - binding '1' to parameter: 1
14:39:40,546 TRACE IntegerType:151 - binding '3' to parameter: 2
14:39:40,546 TRACE IntegerType:151 - binding '4' to parameter: 3
14:39:40,546 DEBUG AbstractBatcher:248 - reusing prepared statement
14:39:40,547 DEBUG SQL:111 - insert into user_tasks (user_id, id, task_id) values (?, ?, ?)
14:39:40,547 TRACE IntegerType:151 - binding '1' to parameter: 1
14:39:40,548 TRACE IntegerType:151 - binding '4' to parameter: 2
14:39:40,548 TRACE IntegerType:151 - binding '5' to parameter: 3
14:39:40,548 DEBUG AbstractCollectionPersister:1194 - done inserting collection: 5 rows inserted
14:39:40,548 DEBUG AbstractBatcher:66 - Executing batch size: 5
14:39:40,550 DEBUG AbstractBatcher:418 - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
14:39:40,550 TRACE AbstractBatcher:562 - closing statement
14:39:40,551 TRACE ConnectionManager:501 - registering flush end
14:39:40,551 TRACE AbstractFlushingEventListener:344 - post flush
14:39:40,551 TRACE JDBCContext:228 - before transaction completion
14:39:40,551 TRACE SessionImpl:421 - before transaction completion
14:39:40,559 DEBUG JDBCTransaction:147 - committed JDBC Connection
14:39:40,559 TRACE JDBCContext:242 - after transaction completion
14:39:40,559 DEBUG ConnectionManager:427 - aggressively releasing JDBC connection
14:39:40,560 DEBUG ConnectionManager:464 - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
14:39:40,560 TRACE DriverManagerConnectionProvider:152 - returning connection to pool, pool size: 1
14:39:40,560 TRACE SessionImpl:450 - after transaction completion
14:39:40,560 TRACE SessionImpl:301 - closing session

Ответы [ 3 ]

3 голосов
/ 27 апреля 2011

Increment определенно плохо, если у вас есть несколько процессов, пишущих в одну и ту же таблицу - вы обязательно столкнетесь.

Так что используйте <<code>generator class="identity"/> и попробуйте.

1 голос
/ 27 апреля 2011

Прошло много времени с тех пор, как я использовал файлы hbm, но не должно ли это быть:

    <id name="id">
        <column name="id" />
        <generator class="native" />
    </id>

?

0 голосов
/ 18 января 2013

У меня такая же ошибка после сброса и восстановления базы данных MySQL. Перезапуск сервера приложений (в моем случае Tomcat) решил эту проблему.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...