|
|
|
@ -58,6 +58,10 @@ public abstract class JpaAbstractDao<E extends BaseEntity<D>, D> |
|
|
|
@Override |
|
|
|
@Transactional |
|
|
|
public D save(TenantId tenantId, D domain) { |
|
|
|
return save(tenantId, domain, false); |
|
|
|
} |
|
|
|
|
|
|
|
private D save(TenantId tenantId, D domain, boolean flush) { |
|
|
|
E entity; |
|
|
|
try { |
|
|
|
entity = getEntityClass().getConstructor(domain.getClass()).newInstance(domain); |
|
|
|
@ -73,14 +77,15 @@ public abstract class JpaAbstractDao<E extends BaseEntity<D>, D> |
|
|
|
entity.setCreatedTime(Uuids.unixTimestamp(uuid)); |
|
|
|
} |
|
|
|
try { |
|
|
|
entity = doSave(entity, isNew); |
|
|
|
entity = doSave(entity, isNew, flush); |
|
|
|
} catch (OptimisticLockException e) { |
|
|
|
throw new EntityVersionMismatchException((getEntityType() != null ? getEntityType().getNormalName() : "Entity") + " was already changed by someone else", e); |
|
|
|
} |
|
|
|
return DaoUtil.getData(entity); |
|
|
|
} |
|
|
|
|
|
|
|
protected E doSave(E entity, boolean isNew) { |
|
|
|
protected E doSave(E entity, boolean isNew, boolean flush) { |
|
|
|
boolean flushed = false; |
|
|
|
EntityManager entityManager = getEntityManager(); |
|
|
|
if (isNew) { |
|
|
|
if (entity instanceof HasVersion versionedEntity) { |
|
|
|
@ -94,24 +99,32 @@ public abstract class JpaAbstractDao<E extends BaseEntity<D>, D> |
|
|
|
if (existingEntity != null) { |
|
|
|
versionedEntity.setVersion(existingEntity.getVersion()); // manually resetting the version to latest to allow force overwrite of the entity
|
|
|
|
} else { |
|
|
|
return doSave(entity, true); |
|
|
|
return doSave(entity, true, flush); |
|
|
|
} |
|
|
|
} |
|
|
|
entity = entityManager.merge(entity); |
|
|
|
/* |
|
|
|
* flushing so that the query is executed right away and the version is incremented, |
|
|
|
* then removing the entity from the persistence context so that it is not affected |
|
|
|
* by next flushes (e.g. when a transaction is committed) to avoid double version increment |
|
|
|
* */ |
|
|
|
entityManager.flush(); |
|
|
|
entityManager.detach(entity); |
|
|
|
flushed = true; |
|
|
|
} else { |
|
|
|
entity = entityManager.merge(entity); |
|
|
|
} |
|
|
|
} |
|
|
|
if (flush && !flushed) { |
|
|
|
entityManager.flush(); |
|
|
|
} |
|
|
|
return entity; |
|
|
|
} |
|
|
|
|
|
|
|
@Override |
|
|
|
@Transactional |
|
|
|
public D saveAndFlush(TenantId tenantId, D domain) { |
|
|
|
D d = save(tenantId, domain); |
|
|
|
getRepository().flush(); |
|
|
|
return d; |
|
|
|
return save(tenantId, domain, true); |
|
|
|
} |
|
|
|
|
|
|
|
@Override |
|
|
|
|