How can I refresh the entity inside a transactional method so that the properties changed by a trigger become visible?
I have a trigger that sets/updates certain columns before an insert/update. Postgres example:
CREATE TRIGGER customer_befins
BEFORE INSERT
ON customer
FOR EACH ROW
EXECUTE PROCEDURE tr_update_managementfields();
On the backend side I have a transactional method that creates and returns the entity:
UPDATE: Added entity mapping.
@MappedSuperclass
public abstract class BaseEntity implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GenericGenerator(name = "IdGenerator", strategy = "demo.IdGenerator")
@GeneratedValue(generator = "IdGenerator")
@Column(columnDefinition = "bpchar", updatable = false)
private String id;
@Column(name = "somedate", columnDefinition = "TIMESTAMP")
private LocalDateTime someDate;
public BaseEntity() {
}
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
public LocalDateTime getSomeDate() {
return this.someDate;
}
public void setSomeDate(LocalDateTime someDate) {
this.someDate = someDate;
}
}
@Entity
public class CustomerEntity extends BaseEntity {
private static final long serialVersionUID = 1L;
@Column(name = "name", nullable = false)
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public interface ICustomerRepository extends JpaRepository<CustomerEntity, String>, JpaSpecificationExecutor<CustomerEntity> {
}
@Service
public class CustomerService {
private final EntityManager entityManager;
private final ICustomerRepository repository;
public CustomerService(EntityManager entityManager, ICustomerRepository repository) {
this.entityManager = entityManager;
this.repository = repository;
}
@Transactional
public CustomerEntity createEntity(...) {
CustomerEntity entity = new CustomerEntity();
// ...
entity = repository.save(entity);
// I need the values changed by the trigger here
return entity;
}
After the save, the properties changed by the trigger are not visible in the entity. In this example the column of the property "someDate" is changed by the trigger. First, I tried to refresh the entity via "entityManager.refresh(entity);" directly after calling "repository.save()". However, this leads to:
jakarta.persistence.EntityNotFoundException: No row with the given identifier exists: [this instance does not yet exist as a row in the database
I already checked the following questions, but I did not found a working solution: