开发者

Hibernate second-level cache composite-id

开发者 https://www.devze.com 2023-03-13 18:14 出处:网络
I am trying to cache an object in Hibernate\'s second level cache that has a composite-id mapped in my persistence-mapping file.The logs say that the first time I run the query, the class mapped as th

I am trying to cache an object in Hibernate's second level cache that has a composite-id mapped in my persistence-mapping file. The logs say that the first time I run the query, the class mapped as the composite-id is put in the cache. However, when I run the query a second time, the object is not pulled from the cache. It is instead running the query again.

Does Hibernate have a problem with second-level caching composite ids?

Relevant info:

  1. Using Hibernate 3.1, ehcache 2.4.2
  2. Composite ID class implements serializable
  3. I am using a new Hibernate session when running the query a second time
  4. I am using hibernateTemplate.load(Class, ID) to retrieve the object

This is how I'm constructing my ID and executing my query:

CompositeId id = new CompositeId(date, sessionId);
UserDetails user = (UserDetails) hibernateTemplate.load(UserDetails.class, id);

And this is how 开发者_JAVA技巧my persistence-mapping file defines the above:

<class name="com.entities.UserDetails"
        table="USER_DETAILS" 
        lazy="false">
    <cache usage="read-write"/>

    <composite-id name="userId" class="com.entities.CompositeId" unsaved-value="undefined">
        <key-property name="userSessionId" column="SESSION_ID" />
        <key-property name="dateCreated" column="DATE_CREATED" type="date" />
    </composite-id>

EDIT: The plot thickens....

When I changed this to read-only cache policy, it worked fine. Transactional cache behavior seems to be extremely unpredictable. Can anyone explain why the above happened with a read-write cache, yet worked fine with read-only? This table is not being updated so not sure why transactional semantics would change things in that instance.


This looks like a reported bug with Hibernate. Seems that as a workaround, you may be able to successfully hit the cache if you use the same instance of your composite key, as opposed to one that is .equals().

There is also a patch on the bug report, you could perhaps apply it yourself and roll your own patched Hibernate build.

0

精彩评论

暂无评论...
验证码 换一张
取 消