开发者

Hibernate entity caching on a field other than the id

I have an entity with a dataless primary key (@Id) and an attribute that is unique, but meaningful (stockTicker). Clients of this entity sometimes request results by the @Id criteria and sometimes by the stockTicker criteria. I'd like the cache to be able to hit on either criteria. The @Id criteria is no problem. I can think of 2 solutions for cache hits on stockTicker. I can create a separate entity and set the @Id to the stockTicker which will allow the second level cache to be used. Alternatively I can turn on query cache. I don't really want to turn on query cache because there are other entities in the same EntityManager that I don't really want cached. Thus I'd have to break this query out into a separate persistence unit. Please suggest if one开发者_StackOverflow of these approaches is correct, or if there is a better option.

@Entity
@Immutable
@Cache(usage= CacheConcurrencyStrategy.READ_ONLY)
@Table(name = "Security")
public class SecurityEntity {
    @Id
    private Integer id;
    private String stockTicker;
...


Ideally, my preference would be to use the stock ticker as the ID. This seems like a case where you have a perfectly good natural key, and so no need for a surrogate.

However, given your object model, i'd go for the query cache option. Fortunately, it seems that Hibernate lets you control the query cache in a reasonably fine-grained way:

As mentioned above, most queries do not benefit from caching or their results. So by default, individual queries are not cached even after enabling query caching. To enable results caching for a particular query, call org.hibernate.Query.setCacheable(true). This call allows the query to look for existing cache results or add its results to the cache when it is executed.

You're very sensibly using the JPA interface to Hibernate, but with that, i think you can get the same effect using a query hint:

org.hibernate.cacheable: Whether or not a query is cacheable ( eg. new Boolean(true) ), defaults to false

I am by no means a Hibernate expert, but it doesn't seem that you would need to move your entity into solitary confinement in its own persistent unit to enable query caching for it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜