Hibernate 和 Ehcache - 如何确保每个“选择”都有效通过实体缓存?
我有一个实体(带有 Hibernate 查询接口的 JPA 注释),它具有两个属性的复合业务键(一个 external-id
和一个 subsidiary-id
[这是一个外键] ]) 和主数据库键。
我有一个 JavaSE 多线程进程,它“相对于子公司”运行,并且需要使用该组合键查询/更新/插入这些实体(它获取这些 external-ids
的数据集)。
我可以保证,一旦这样的进程加载,其他进程将不会尝试插入/更新/删除该子公司。
我想要的是在启动时加载该子公司的所有现有实体,然后让每个查询对一对 [externalId,subsidiaryId]
进行缓存,并且仅当未命中时才进行缓存数据库。如果进程中的一个线程插入一个实体,我当然希望将其添加到该缓存中。
最好的做法是什么?
我知道有查询缓存,但据我所知,每 [externalId,subsidiaryId]
对的第一次仍然会错过。
谢谢,如果有任何不清楚的地方,请询问
更新
我不得不停止调查这个问题,但现在我又回到了这个问题,我认为只有查询缓存和 JB Nizet 的答案是唯一适用的似乎是合理的。
我会接受 JB Nizet 的回答,因为它很有趣,我可能会使用它(还不确定)。
I have an entity (JPA annotations with Hibernate query interface) which has a composite business key of two properties (an external-id
and a subsidiary-id
[that's a foreign key]) and a primary db key.
I have a JavaSE multi-threaded process which runs "with respect to a subsidiary" and needs to query/update/insert those entities using that composite key (it gets datasets of those external-ids
).
I can guarantee that once such a process loads no other process will try to insert/update/remove that subsidiary.
What I want is to load all existing entities of that subsidiary on startup and then have every query for a pair of [externalId,subsidiaryId]
to go through the cache and only if there's a miss to go through the db. In case one of the threads from the process inserts an entity I of course want that to be added to that cache.
What's the best course of action?
I know there's query caching but from what I can gather that will still be a miss the first time of every [externalId,subsidiaryId]
pair.
Thanks and if there's anything which I'm not clear about please ask
Update
I had to stop investigating this issue but now that I've come back to it I think that it's seems reasonable that only the query cache and JB Nizet's answer are the only ones applicable.
I'll accept JB Nizet's answer as it is interesting and I might use it (not sure yet).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将为实体使用二级缓存,在启动时查询所有子公司的实体(这将填充二级缓存),并初始化一个仅映射
[externalId,subsidiaryId] 到 <代码>[id]。
然后,每次搜索具有给定
[externalId,substitutionId]
的实体时,首先从应用程序缓存中获取其 ID,然后I would use a second-level cache for the entity, query for all the subsidiry's entities at startup (this will fill the second-level cache), and initialize an application cache which would just map
[externalId, subsidiaryId]
to[id]
.Then, each time you're searching for an entity with a given
[externalId, subsidiaryId]
, first get its ID from the application cache, then