Browse Source

Create versioned entities with preset ids through persist

pull/16341/head
Viacheslav Klimov 2 months ago
parent
commit
e420bec7ce
Failed to extract signature
  1. 12
      dao/src/main/java/org/thingsboard/server/dao/sql/JpaAbstractDao.java
  2. 16
      dao/src/test/java/org/thingsboard/server/dao/sql/device/JpaDeviceDaoTest.java

12
dao/src/main/java/org/thingsboard/server/dao/sql/JpaAbstractDao.java

@ -10,7 +10,6 @@ import jakarta.persistence.EntityManager;
import jakarta.persistence.OptimisticLockException;
import jakarta.persistence.PersistenceContext;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.jdbc.core.JdbcTemplate;
@ -113,13 +112,10 @@ public abstract class JpaAbstractDao<E extends BaseEntity<D>, D>
if (entity.getUuid() == null) {
getEntityManager().persist(entity);
} else {
if (entity instanceof HasVersion) {
/*
* Hibernate 6 does not allow creating versioned entities with preset IDs.
* Bypassing by calling the underlying session directly
* */
Session session = getEntityManager().unwrap(Session.class);
session.save(entity);
if (entity instanceof HasVersion versionedEntity) {
// a null version makes persist() treat the entity as new despite its preset id
versionedEntity.setVersion(null);
getEntityManager().persist(entity);
} else {
entity = getEntityManager().merge(entity);
}

16
dao/src/test/java/org/thingsboard/server/dao/sql/device/JpaDeviceDaoTest.java

@ -15,6 +15,7 @@ import org.thingsboard.server.common.data.Device;
import org.thingsboard.server.common.data.DeviceProfile;
import org.thingsboard.server.common.data.DeviceProfileType;
import org.thingsboard.server.common.data.DeviceTransportType;
import org.thingsboard.server.common.data.exception.EntityVersionMismatchException;
import org.thingsboard.server.common.data.id.CustomerId;
import org.thingsboard.server.common.data.id.DeviceId;
import org.thingsboard.server.common.data.id.TenantId;
@ -112,6 +113,21 @@ public class JpaDeviceDaoTest extends AbstractJpaDaoTest {
assertThat(device.getVersion()).isEqualTo(3);
}
@Test
public void testSaveDevice_presetId_staleVersionRejected() {
Device device = getDevice(tenantId1, customerId1, "preset-id-stale");
device = saveDevice(tenantId1, device);
deviceIds.add(device.getUuidId());
Device stale = new Device(device);
stale.setVersion(device.getVersion());
device.setName(device.getName() + "x");
saveDevice(tenantId1, device);
stale.setName(stale.getName() + "y");
assertThatThrownBy(() -> saveDevice(tenantId1, stale)).isInstanceOf(EntityVersionMismatchException.class);
}
@Test
public void testSaveDevice_versionIncrement_noChanges() {
Device device = getDevice(tenantId1, customerId1, "1ewfewf2");

Loading…
Cancel
Save