java 同一张桌子上的 2 个 JPA 实体
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1667930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
2 JPA entities on the same table
提问by John Rizzo
Let's say I've a table with 200 columns and most of them are never used.
假设我有一个包含 200 列的表,其中大部分从未使用过。
I map SmallEntity to the 10 columns that are used often. I use it in the associations with other entities. It loads fast, consume few memory and makes me happy.
我将 SmallEntity 映射到经常使用的 10 列。我在与其他实体的关联中使用它。它加载速度快,占用内存少,让我很高兴。
But sometimes I need to display the 200 columns. I'd like to map the BigEntity class on the 200 columns. It is bound to no other entity, it has no association.
但有时我需要显示 200 列。我想在 200 列上映射 BigEntity 类。它不绑定到任何其他实体,没有关联。
Question: Do you have any experience doing that? Are you aware of any trouble that Hibernate would have, as for example in first level cache, dirty checking and entity lifecycle in general?
问:你有这样做的经验吗?您是否知道 Hibernate 会遇到任何麻烦,例如在一级缓存、脏检查和一般的实体生命周期方面?
采纳答案by ChssPly76
The most straightforward way to do this is to map properties you don't use often as lazy:
最直接的方法是映射你不经常使用的属性作为惰性:
<property name="extendedProperty" lazy="true" />
... or using Annotations ...
@Basic(fetch = FetchType.LAZY)
String getExtendedProperty() { ... }
Hibernate would not load such properties initially; instead they'll be loaded on demand (when first accessed). You can force Hibernate to load all properties by using fetch all propertiesclause in your HQL query.
Hibernate 最初不会加载这些属性;相反,它们将按需加载(第一次访问时)。您可以通过fetch all properties在 HQL 查询中使用子句来强制 Hibernate 加载所有属性。
Another possible scenario is to actually map two completely separate entities to the same table but make one of them immutable. Keep in mind that they willbe treated as different entities by Hibernate, with first / second level cache being completely separate for both (which is why immutability is important).
另一种可能的情况是实际上将两个完全独立的实体映射到同一个表,但使其中一个不可变。请记住,它们将被 Hibernate 视为不同的实体,一级/二级缓存对两者完全分开(这就是不变性很重要的原因)。
You will NOTbe able to achieve this functionality via inheritance mapping because Hibernate alwaysreturns an actual concrete entity type. Take a look at my answer to Hibernate Inheritance Strategyquestion for a detailed explanation.
你将不能够实现通过继承映射此功能,因为Hibernate总是会返回一个实际的具体的实体类型。查看我对Hibernate Inheritance Strategy问题的回答以获得详细说明。

