How do I use Hibernate's second level cache with JPA?

前端 未结 1 1487
梦谈多话
梦谈多话 2021-02-15 23:52

I am implementing an Entity Attribute Value based persistence mechanism. All DB access is done via Hibernate. I have a table that contains paths for nodes, it is extremely simp

相关标签:
1条回答
  • 2021-02-16 00:25

    Ok, I found it. My problem was that, cached query was keeping only Ids of query results in the cache, and it was (probably) going back to db to get the actual values, rather than getting them from the second level cache.

    The problem is of course, the query did not put those values to second level cache, since they were not selected by primary id. So the solution is to use a method that will put values to second level cache, and with hibernate 4.1, I've manage to do this with natural id. Here is the function that either inserts or returns the value from cache, just in case it helps anybody else:

    private UUID persistPath(String pPath) throws Exception{
            org.hibernate.Session session = (Session) entityManager.getDelegate();
            NodePath np = (NodePath) session.byNaturalId(NodePath.class).using("path", pPath).load();
            if(np != null)
                return np.getId();
            else {//no such path entry, so let's create one
                NodePath newPath = new NodePath();
                newPath.setPath(pPath);
                entityManager.persist(newPath);
                return newPath.getId();
            }
    
    
        }
    
    0 讨论(0)
提交回复
热议问题