Modify an Object Using Hibernate PreInsertEventListener

I am using Hibernate 4.1 trying to call PreInsertEventListener to update an object before inserting it into the database based on the article here: http://anshuiitk.blogspot.ca/2010/11/hibernate-pre-database-opertaion-event.html

public class PreInsertListener implements PreInsertEventListener { @Override public boolean onPreInsert(PreInsertEvent event) { Product product = (Product)event.getEntity(); String barcode = "B" + product.getProductId(); product.setBarcode(barcode); // Update the state value that will be persisted String[] properties = event.getPersister().getEntityMetamodel().getPropertyNames(); List<String> propertiesList = Arrays.asList(properties); event.getState()[propertiesList.indexOf('barcode')] = barcode; } } 

When I debug it, it executes the PreInsertListener code, but the values ​​inserted into the database do not contain any code changes. This was used to work in Hibernate 3. What am I missing here?

+6
source share
2 answers

Just make sure you don't get into the approach-3 issue mentioned in the blog post you shared above. If you have actions to insert and update your object in one transaction, your actions for previewing preInsert will be overridden by the update action.

- Post from a blog post ( http://anshuiitk.blogspot.ca/2010/11/hibernate-pre-database-opertaion-event.html )

Hibernate generates a prepared statement and populates the parameters from the 'state' array present in the event. Therefore, any changes made to this state array are reflected in the sql statement, the generated sleep mode, and finally in the database. Insert and update events have another copy of this state array.

The pre-insert presenter is called before the pre-update event (if the insert, as well as the update occurs). This happens when an object is created, saved, and then changed in a single transaction. This will lead to two separate sql statements, first there will be an insert statement, and the second will be an update statement on the same object. With the insert statement, when we set only insertUser and insertTime in our PreInsertEventListener , not updateUser and updateTime . The generated statement will look like

 insert into entity (id, .... , insert_user, insert_time, update_user, update_time) values (1, .... 'test', '21.11.2010 16:10:00', null, null) 

with PreUpdateEventListener generated SQL update will look like

 update entity set id=1 .... , insert_user=null, insert_time=null, update_user='test', update_time='21.11.2010 16:10:00' 
+3
source

Use the saveorupdate event listener instead.

0
source

Source: https://habr.com/ru/post/945194/


All Articles