tags:

views:

684

answers:

1

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?

+1  A: 

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.

ChssPly76
Thank you very much for this great answer!
John Rizzo
It seems that lazy fetching of properties require bytecode instrumentation. Is that so common on projects?That is from Hibernate Annotations guide:<i>To enable property level lazy fetching, your classes have to be instrumented: bytecode is added to the original one to enable such feature, please refer to the Hibernate reference documentation. If your classes are not instrumented, property level lazy loading is silently ignored.</i>
John Rizzo
Yes, bytecode instrumentation is necessary for lazy properties but it's easy to add during build (http://docs.jboss.org/hibernate/stable/core/reference/en/html/performance.html#performance-fetching-lazyproperties). It's not very common (in my experience) because the use case for lazy properties (as opposed to lazy associations) is not that common but it's not exceedingly rare either. It has certainly been done before and is production-ready if that's your concern.
ChssPly76