2 JPA entities on the same table
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 colu开发者_StackOverflow社区mns. 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.
精彩评论