为什么Hibernate在我的表上生成重复的主键

时间:2018-07-27 08:01:30

标签: java hibernate h2

我正在使用Hibernate 4.3.11和H2数据库1.3.172

我遇到了这个错误

org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:129)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)
at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)
at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:492)
at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:197)
at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:181)
at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:216)
at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:334)
at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:289)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:195)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:126)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:209)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:55)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:49)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:90)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:715)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:707)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:702)
at com.jthink.songkong.db.SongChangesCache.saveMatchedToRelease(SongChangesCache.java:29)
at com.jthink.songkong.analyse.analyser.SongSave.saveSongChangedDetailsToDb(SongSave.java:416)
at com.jthink.songkong.analyse.analyser.SongSave.call(SongSave.java:163)
at com.jthink.songkong.analyse.analyser.SongSave.call(SongSave.java:73)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:748)
Caused by: org.h2.jdbc.JdbcSQLException: Unique index or primary key violation: "PRIMARY KEY ON PUBLIC.SONGCHANGES(ID)"; SQL statement:
insert into SongChanges (id, field, newValue, originalValue, recNo, reportId, type, version) values (null, ?, ?, ?, ?, ?, ?, ?) [23505-172]

我之前从未见过此错误,我的songchanges表使用了标准 主键生成方式

@Id
@GeneratedValue
private Integer      id;

我的Session不是在线程之间共享的,但是有多个线程可以通过自己的会话写入songchanges表中,但是为什么这很重要?

我的配置如下

private static void addEntitiesToConfig(Configuration config) {
    config.addAnnotatedClass(MusicBrainzReleaseWrapper.class);
    config.addAnnotatedClass(MusicBrainzReleaseGroupWrapper.class);
    config.addAnnotatedClass(MusicBrainzArtistWrapper.class);
    config.addAnnotatedClass(DiscogsReleaseWrapper.class);
    config.addAnnotatedClass(AcoustidWrapper.class);
    config.addAnnotatedClass(PuidWrapper.class);
    config.addAnnotatedClass(Song.class);
    config.addAnnotatedClass(CoverImage.class);
    config.addAnnotatedClass(CoverArt.class);
    config.addAnnotatedClass(MatchedToMusicBrainz.class);
    config.addAnnotatedClass(MatchedToAllMusicGuide.class);
    config.addAnnotatedClass(MatchedToDiscogs.class);
    config.addAnnotatedClass(SongProcessed.class);
    config.addAnnotatedClass(SongChanges.class);
    config.addAnnotatedClass(DeleteDuplicates.class);
    config.addAnnotatedClass(AcoustidRecordingIdPair.class);
    config.addAnnotatedClass(ITunesTrack.class);
    config.addAnnotatedClass(Report.class);
}

public static Configuration getInitializedConfiguration() {
    Configuration config = new Configuration();
    config.setProperty("hibernate.connection.driver_class", "org.h2.Driver");
    config.setProperty("hibernate.connection.url", "jdbc:h2:" + Db.DBFOLDER + "/" + Db.DBNAME + ";FILE_LOCK=SOCKET;MVCC=TRUE;DB_CLOSE_ON_EXIT=FALSE;CACHE_SIZE=50000");
    config.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
    System.setProperty("h2.bindAddress", InetAddress.getLoopbackAddress().getHostAddress());
    config.setProperty("hibernate.connection.username", "******");
    config.setProperty("hibernate.connection.password", "******");
    config.setProperty("hibernate.c3p0.numHelperThreads", "10");
    config.setProperty("hibernate.c3p0.min_size", "20");
    config.setProperty("hibernate.c3p0.max_size", "200");
    config.setProperty("hibernate.c3p0.timeout", "300");
    config.setProperty("hibernate.c3p0.maxStatementsPerConnection", "50");
    config.setProperty("hibernate.c3p0.idle_test_period", "3000");
    config.setProperty("hibernate.c3p0.acquireRetryAttempts", "10");
    addEntitiesToConfig(config);
    return config;
}

我得到这样的会话

  public static Session beginTransaction() {
        Session hibernateSession = getSession();
        hibernateSession.beginTransaction();
        return hibernateSession;
    }

SongChanges类如下

package com.jthink.songlayer;

import org.hibernate.annotations.Table;

import javax.persistence.*;
import java.util.Date;

/**
 *
 */

@Entity
@org.hibernate.annotations.Table(appliesTo="SongChanges",indexes =
@org.hibernate.annotations.Index(name = "IDX_SONG_CHANGES_REPORTID_RECNO",
        columnNames = {"reportId", "recNo"})
)
public class SongChanges
{
    @Id
    @GeneratedValue
    private Integer      id;

    @Column(nullable = false)
    @org.hibernate.annotations.Index(name = "IDX_SONG_CHANGES_REPORTID")
    private Integer      reportId;

    @Column(nullable = false)
    @org.hibernate.annotations.Index(name = "IDX_SONG_CHANGES_RECNO")
    private Integer      recNo;

    private SongFieldKey field;

    @Column(length = 10000)
    private String       originalValue;

    @Column(length = 10000)
    private String       newValue;

    @Version
    private int version;

    private SongChangeType      type;


    public Integer getId()
    {
        return id;
    }

    public void setId(Integer id)
    {
        this.id = id;
    }

    public Integer getReportId()
    {
        return reportId;
    }

    public void setReportId(Integer reportId)
    {
        this.reportId = reportId;
    }

    public Integer getRecNo()
    {
        return recNo;
    }

    public void setRecNo(Integer recNo)
    {
        this.recNo = recNo;
    }

    public SongFieldKey getField()
    {
        return field;
    }

    public void setField(SongFieldKey field)
    {
        this.field = field;
    }

    public String getOriginalValue()
    {
        return originalValue;
    }

    public void setOriginalValue(String originalValue)
    {
        this.originalValue = originalValue;
    }

    public String getNewValue()
    {
        return newValue;
    }

    public void setNewValue(String newValue)
    {
        this.newValue = newValue;
    }

    public SongChangeType getType()
    {
        return type;
    }

    public void setType(SongChangeType type)
    {
        this.type = type;
    }
}

1 个答案:

答案 0 :(得分:0)

正在发生的是,您的id并未生成,正如您在日志文件中看到的值null一样。

有很多方法可以解决这个问题,其中之一就是创建序列。

您可以通过将strategy添加到@GeneratedValue来实现。您将拥有类似的东西:

@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SONG_CHANGES_SEQ")
@SequenceGenerator(sequenceName = "SONG_CHANGES_SEQ", allocationSize = 1, name = "SONG_CHANGES_SEQ")
private Integer id;