Description of the Problem:
Hi everyone!
I’m facing an issue related to the use of AfterInsertEntityListener
. Let me provide a simplified example:
- In the system, there is a Locations directory (class
Location
). - Two screens are implemented for it:
- Browse — for displaying the table of locations.
- Editor — for creating and editing records.
I want to add a listener that triggers after a record is inserted into the database but before the transaction is committed. For this, I’m using AfterInsertEntityListener
. In this listener, I execute an SQL query to update the name
field.
Condition:
- The use of SQL is mandatory (in the actual task, a complex recursive script is executed, which must run after the record is inserted).
Expected Behavior:
- After creating a record in the Editor screen, the listener updates the
name
field via SQL. - When returning to the Browse screen, I expect to see the updated
name
value (e.g.,"Name - test"
).
Actual Behavior:
- The updated value is displayed only after clicking the Refresh button in the Browse screen.
Documentation Quote:
AfterInsertEntityListener
TheonAfterInsert()
method is called after the record is inserted into the database but before the transaction is committed.
In this method, you cannot modify the current persistent context, but you can make changes to the database usingQueryRunner
.
Listener Code:
@Component(“am_BaseUuidEntityListener”)
public class BaseUuidEntityListener implements AfterInsertEntityListener {
@Inject
protected Persistence persistence;
@Override
public void onAfterInsert(BaseUuidEntity baseUuidEntity, Connection connection) {
if (baseUuidEntity instanceof Location) {
QueryRunner runner = new QueryRunner();
DbTypeConverter dbTypeConverter = persistence.getDbTypeConverter();
String sqlQuery = "UPDATE AM_LOCATION SET name = '" + baseUuidEntity.getValue("name") + " - новый' WHERE id = ?";
try {
runner.update(
connection,
sqlQuery,
dbTypeConverter.getSqlObject(baseUuidEntity.getId())
);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}}
An example of a problem:
After creating the location:
After the button has been pressed Refresh:
Question:
Why isn’t the updated value displayed immediately upon returning to the Browse screen? How can I resolve this issue so that the changes are reflected without manually refreshing the table?