2个JPA实体放在同一张桌子上 [英] 2 JPA entities on the same table

查看:91
本文介绍了2个JPA实体放在同一张桌子上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我将SmallEntity映射到经常使用的10列。我在与其他实体的关联中使用它。它加载速度快,消耗少量内存并且让我开心。

但是有时我需要显示200列。我想在200列上映射BigEntity类。它没有其他实体,它没有任何关联。



问题:你有什么经验吗?您是否知道Hibernate会遇到什么麻烦,例如在第一级缓存中,脏检查和实体生命周期一般?

解决方案

最直接的方法是将不经常使用的属性映射为 lazy

 < property name = extendedPropertylazy =true/> 

...或使用注释...

@Basic(fetch = FetchType.LAZY)
String getExtendedProperty(){...}

Hibernate最初不会加载这些属性;相反,它们会按需加载(第一次访问时)。你可以强制Hibernate使用 在HQL查询中获取所有属性 子句。

另一种可能的方案是实际映射两个完全独立的实体到同一个表,但使其中一个不可变的。请记住,它们作为Hibernate的不同实体对待,其中第一个/第二个级别缓存完全独立于两者(这就是为什么不变性很重要)。



您将 NOT 通过继承映射实现此功能,因为Hibernate 始终返回实际的具体实体类型。看看我的答案 Hibernate Inheritance Strategy 问题的详细信息说明。

Let's say I've a table with 200 columns and most of them are never used.

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.

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.

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?

解决方案

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 properties clause in your HQL query.

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 will be treated as different entities by Hibernate, with first / second level cache being completely separate for both (which is why immutability is important).

You will NOT be able to achieve this functionality via inheritance mapping because Hibernate always returns an actual concrete entity type. Take a look at my answer to Hibernate Inheritance Strategy question for a detailed explanation.

这篇关于2个JPA实体放在同一张桌子上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆