Spring Jpa different object already associated

ERROR: A different object with the same identifier value was already associated with the session

Solution: See if an existing ID already exist, if not persist record. If same ID found, merge with existing record

@Override
	@Transactional(value="dwTransactionManager", propagation=Propagation.REQUIRES_NEW)
	public void insertLog(Error[] errorRecords, Long recordId, String salesforceId, String objectName) {
		for (Error errorRecord : errorRecords){
			try {
				DWLog log = new DWLog();
				log.setId(new BigDecimal(recordId));
				Calendar cal = Calendar.getInstance();
				log.setLastSyncD(cal.getTime());
				log.setLastSyncMsg("ERROR CODE: " + errorRecord.getStatusCode() + " MESSAGE: " + errorRecord.getMessage());
				log.setObjectSync(objectName);
				if (entityManager.find(DWLog.class,log.Id)!=null){
					entityManager.merge(log);	
				}else{
					entityManager.persist(log);	
				}
			} catch (Exception e) {
				logger.error("LogDaoImpl.insertLog(): " + e.getMessage());
			}
		}
	}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: