Entity Not indexed automatically with JPQL Update

We have entity marked for indexing as
@Entity
@Table(name = “A”)
@Indexed(index=“A”)
public class A

Now, when this entity is updated using merge() of entitymanager, it is updated automatically in the index, but when entity is updated using JPQL, index is not getting updated.
StringBuilder query = new StringBuilder("UPDATE A a ");
query.append("SET a.status =‘GK’ ");
query.append(“WHERE a.id = 12273928”);
Query dynamicQuery = getEntityManager().createQuery(query.toString());
dynamicQuery.executeUpdate();

Do automatic indexing only works with methods for update/delete and not with JPQL update/delete?

That’s right, automatic indexing only works with direct operations on the session (persist, …). JPQL update/delete queries are translated into SQL and sent to the database as is. As a result, Hibernate ORM (and thus Hibernate Search) are not aware of which entities got updated/deleted, and cannot reflect these changes in the index.

You will need to either:

  • Perform your updates directly in a session by loading the entities one by one, modifying them and peristing the changes using the Session.
  • Trigger reindexing manually for the impacted entities after the fact: see Hibernate Search 5.11.12.Final: Reference Guide

Note that’s not just a limitation of Hibernate Search. If you have a second-level cache, you will need to perform evictions manually for the entities affected by your JPQL update/delete queries, because Hibernate ORM cannot do it by itself.

As for Hibernate Search, we’re planning on solving this by adding Debezium integration, which would allow us to detect all database changes, but that’s still a long-term goal.

Thanks Yrodiere for the confirmation