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.
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. 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".
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.
Side note this works fine if the data isnt in the database it loads everything.