I am getting error
aliases expected length is 1; actual length is 4
at org.hibernate.transform.CacheableResultTransformer.transformTuple
I
Hibernate can’t know what you are doing when you execute a native sql query and therefore it can’t know what caches need to be invalidated. As long as hibernate doesn’t know which caches are affected it must assume that all data is invalid to ensure data consistency. This means that hibernate will invalidate all caches.
Fortunatly the hibernate API let you specify the entities or query spaces that are affected by your query. Tell hibernate which tables are affected by your query and hibernate will only invalidate caches that are based on that data.
SQLQuery sqlQuery = session.createSQLQuery("UPDATE CUSTOMER SET ... WHERE ...");
sqlQuery.addSynchronizedEntityClass(Person.class);
int updatedEntities = sqlQuery.executeUpdate();
with entity name
sqlQuery.addSynchronizedEntityClass(Person.class);
sqlQuery.addSynchronizedEntityName("com.link_intersystems.xhibernate.testclasses.Person");
sqlQuery.addSynchronizedQuerySpace("SOME_TABLE");
Sometimes you want to execute a native query that doesn’t change any data. To prevent hibernate from invalidating the second level caches you can add an empty query space synchronization.
SQLQuery sqlQuery = session.createSQLQuery("ALTER SESSION SET NLS_COMP = 'BINARY'");
sqlQuery.addSynchronizedQuerySpace("");
/*
* Only the empty query space "" will be invalidated.
* So no cache will be invalidated, because no table with an empty name exists
*/
int updatedEntities = sqlQuery.executeUpdate();
in hibernate mapping xml
<sql-query name="setNLSCompBinary">
<!-- an empty synchronize tag prevents hibernate from invalidating second level caches -->
<synchronize table="" />
ALTER SESSION SET NLS_COMP = 'BINARY'
</sql-query>
impact-of-native-sql-queries-on-hibernates-second-level-cache
OMG, you should not use cache with native queries, hibernate is not designed for that:
https://www.link-intersystems.com/blog/2011/10/08/impact-of-native-sql-queries-on-hibernates-second-level-cache/
In your case, EHCache can only be used with JPQL queries. That will also mean you will have to rewrite your query not to use sub-selects, unions or similar native sql constructions.