Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate Envers - Doesn't write audit records for createQuery(...).executeUpdate(), only .persist() and .merge()

I have 3 ways things get written to the DB

public void create(T object) {
    entityManager.persist(object);
}

public void update(T object) {
    object = entityManager.merge(object);
}

public int updateStatus(String id, String status) {

    final int changes =
                entityManager.createQuery("update item set state = :newState," +
                        " last_modified = current_timestamp" +
                        " where id = : id ")
                    .setParameter("newState", status)
                    .setParameter("id", id)
                    .executeUpdate();

            return changes;
}

The problem I have, is in order to get the Hibernate Envers to actually write the audit records to the corrsponsing x_aud and revinfo DB tables. It only works successfully for '.persist()' or '.merge()'. I cannot get it to work for 'createQuery(...).executeUpdate()'

Am I missing something or does it just not work for this. The problem is, a lot of my code has been written using .executeUpdate and not merge, so really I need this to work with the existing code.

Can anyone help please?

like image 630
babb Avatar asked Dec 12 '22 19:12

babb


2 Answers

No, Envers won't work if you are using executeUpdate. That is because the update doesn't pass through Hibernate's event mechanism, so Envers has no chances of intercepting the change, and writing the audit.

like image 158
adamw Avatar answered Apr 27 '23 05:04

adamw


It looks like Avinash T. is right - if you want to create native SQL query, use createNativeQuery(String sqlString) method of EntityManager. Using createQuery(String ejbqlString) is only possible if you're using EJB QL. Hope it would help.

like image 42
bsiamionau Avatar answered Apr 27 '23 06:04

bsiamionau