Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 826
John Rizzo Avatar asked Nov 03 '09 15:11

John Rizzo


People also ask

Can we define two entity in one table?

Yes, you can map two or more entities to the same database table.

How do I join two entities in JPA?

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.

How do I return multiple entities in JPA query?

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.

Can one entity have multiple tables?

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.


1 Answers

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.

like image 81
ChssPly76 Avatar answered Sep 21 '22 12:09

ChssPly76