简体   繁体   English

Hibernates session.saveOrUpdate是如何工作的?

[英]How does Hibernates session.saveOrUpdate work?

I'm new to hibernate and trying to understand it better. 我是新手来休眠并试图更好地理解它。 I've been attempting to ingest data into my database and on my Track Table there is a unique constraint on the track_uuid. 我一直在尝试将数据摄取到我的数据库中,并且在Track Table上对track_uuid有一个独特的约束。

I've attempted to do just a save and catch the exception and move on to next insert however I started using up to many connections. 我试图只做一个保存并捕获异常并转到下一个插入但是我开始使用多达几个连接。

So I started looking around and found that a session has a function saveOrUpdate. 所以我开始环顾四周,发现会话有一个函数saveOrUpdate。 http://www.javabeat.net/difference-between-hibernates-saveupdate-and-saveorupdate-methods/ http://www.javabeat.net/difference-between-hibernates-saveupdate-and-saveorupdate-methods/

However when I change my save to saveOrUpdate I continue to get an error saying duplicate key value violates unique constraint "track_track_uuid_key". 但是,当我将保存更改为saveOrUpdate时,我继续收到错误,指出重复键值违反了唯一约束“track_track_uuid_key”。

My code: 我的代码:

/**
 * @param p_track the track to parse
 * @param p_dbTrackMessage the database track message
 * @param p_session the database session
 * @return {@link database.model.Track} Returns the ingested database track
 * @throws Exception error
 */
private static database.model.Track parseTrack(final Track p_track,
        final database.model.TrackMessage p_dbTrackMessage,
        final Session p_session) throws Exception {

    // the db track model
    final database.model.Track dbTrack = new database.model.Track();

    // get and set track uuid
    dbTrack.setTrackUuid(p_track.getTrackUUID());

    // get and set track number
    dbTrack.setTrackNumber(p_track.getTrackNumber());

    // get and set the track excerise indicator
    dbTrack.setTrackExerciseIndicator(EnumDatabaseLoader.loadByName(
            TrackExerciseIndicator.class, p_track.getExerciseIndicator().name(), p_session));

    // get and set track simulation indicator
    dbTrack.setTrackSimulationIndicator(EnumDatabaseLoader.loadByName(
            TrackSimulationIndicator.class, p_track.getSimulationIndicator().name(), p_session));

    // get and set the track status
    final TrackStatus trackStatus = p_track.getTrackStatus();
    if (trackStatus != null) {
        dbTrack.setTrackStatus(EnumDatabaseLoader.loadByName(
                database.model.TrackStatus.class, trackStatus.name(),
                p_session));
    }

    try {
        p_session.getTransaction().begin();
        // save the track
        p_session.save(dbTrack);     //  Error happens here I've attempted to change this to saveOrUpdate getting same error.

        // create the mapping
        final TrackMessageToTrackMapping trackMessageToTrackMapping =
                new TrackMessageToTrackMapping();
        trackMessageToTrackMapping.setTrackMessage(p_dbTrackMessage);
        trackMessageToTrackMapping.setTrack(dbTrack);

        // save the mapping
        p_session.save(trackMessageToTrackMapping);
        p_session.getTransaction().commit();
    }
    catch (Exception exception) {
        exception.printStackTrace();
        p_session.getTransaction().rollback();
        throw exception;
    }

    // return the track
    return dbTrack;
}

So my question is why does a saveOrUpdate not recognize that the record is already there and attempt to update it instead of coming back with the record already exist with a matching unique constraint on 1 of the columns. 所以我的问题是为什么saveOrUpdate不能识别记录已经存在并且尝试更新它而不是返回记录已经存在,其中一列具有匹配的唯一约束。

Side note this works fine if the data isnt in the database it loads everything. 侧注如果数据不在数据库中加载所有内容,这可以正常工作。

saveOrUpdate is only about primary keys, not arbitrary unique constraints. saveOrUpdate仅与主键有关,而不是任意唯一约束。 To decide whether it's a save or update , Hibernate doesn't consult the database at all: it just checks whether the primary key property is set on the object under consideration. 要确定它是save还是update ,Hibernate根本不会查询数据库:它只检查是否在所考虑的对象上设置了主键属性。

Unfortunately it will be quite difficult to make Hibernate generate the appropriate statement which will not fail on unique constraint violation. 不幸的是,让Hibernate生成适当的语句是非常困难的,该语句在唯一约束违规时不会失败。 You don't have direct control over the generated SQL and the syntax is highly database-specific. 您无法直接控制生成的SQL,语法高度特定于数据库。

The stacktrace pasted was showing up error ie "Not able to open db connection". 粘贴的堆栈跟踪显示错误,即“无法打开数据库连接”。 Not related to save or update. 与保存或更新无关。

theexamtime.com theexamtime.com

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM