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?
Yes, you can map two or more entities to the same database table.
The only way to join two unrelated entities with JPA 2.1 and Hibernate versions older than 5.1, is to create a cross join and reduce the cartesian product in the WHERE statement. This is harder to read and does not support outer joins. Hibernate 5.1 introduced explicit joins on unrelated entities.
In order to create a query returning multiple different entities, we need to do 2 things. Firstly, we need to list entities that we want to return in the SELECT part of the SQL Query, separated by a comma. Secondly, we need to connect them with each other by their primary and corresponding foreign keys.
Solution: Yes, you can map an entity to 2 database tables in 2 simple steps: You need to annotate your entity with JPA's @Table and @SecondaryTable annotations and provide the names of the first and second table as the value of the name parameters.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With