我刚开始冬眠。我正在尝试将记录插入到我的MySQL DB中。当我运行Java应用程序时,以及当我更改代码中的细节并尝试再次运行它时,第一条记录被正确地插入。它会抛出重复密钥或完整性约束的错误。我的XML是
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.college.Student" table="STUDENT">
<id column="ID" name="id" type="long" />
<property column="STUDENT_NAME" name="name" type="string" />
<property column="DEGREE" name="degree" type="string" />
<property column="ROLL" name="roll" type="string" />
<property column="PHONE" name="phone" type="string" />
</class>
</hibernate-mapping>我想我需要更改这个配置文件或Hibernate.cfg.xml,因为它是一个主键。请给我建议。
以下是错误
WARN: SQL Error: 1062, SQLState: 23000
Feb 18, 2016 11:49:36 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Duplicate key or integrity constraint violation message from server: "Duplicate entry '0' for key 'PRIMARY'"
Feb 18, 2016 11:49:36 AM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
Feb 18, 2016 11:49:36 AM org.hibernate.internal.SessionImpl$5 mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [could not execute statement]
Exception in thread "main" org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:112)发布于 2016-02-18 06:31:48
似乎您没有增加您的主键列,您将不得不这样做
<id column="ID" name="id" type="long" >
<generator class="increment" />
</id>发布于 2016-02-18 06:34:20
发布于 2016-02-18 06:48:38
您需要一个id列的自动增量。
对于MySQL来说,最好的选择是使用identity生成器,因为MySQL本机支持它。
<id column="ID" name="id" type="long">
<generator class="identity"/>
</id>Hibernate将创建一个带有auto_increment列的表,而MySQL将关注自动增量id。
create table STUDENT (
ID bigint not null auto_increment,
...
)使用其他生成器并不是最优的,因为Hibernate将使用额外的查询和表(hibernate_sequence)来增加id。
https://stackoverflow.com/questions/35474373
复制相似问题