Hibernate Ehcache NOT working for SQL Native query cache

前端 未结 3 2051
清歌不尽
清歌不尽 2021-02-06 07:50

I am getting error

aliases expected length is 1; actual length is 4
    at org.hibernate.transform.CacheableResultTransformer.transformTuple

I

相关标签:
3条回答
  • 2021-02-06 08:01

    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

    0 讨论(0)
  • 2021-02-06 08:16

    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/

    0 讨论(0)
  • 2021-02-06 08:21

    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.

    0 讨论(0)
提交回复
热议问题