开发者

Mapping an relationship without knowledge of concrete class in Hibernate

开发者 https://www.devze.com 2023-03-11 07:37 出处:网络
There are many topics on abstract mapping in Hibernate, but I couldn\'t find something that matches my case.

There are many topics on abstract mapping in Hibernate, but I couldn't find something that matches my case.

Problem:

My domain model consists of several entities, which don't inherit from each other. For example:

  • Employee
  • Group
  • Department
  • Report

Where:

Employee <-> Group (n:m), Employee -> Department (n:1)

As far as this goes, no problem. But:

I want to be able to map Report to either one of Employee, Group or Department (1:1). (The example is simplified as Report should be mappable to many more different other entities). Every entity must reside in its own table, as different externals want to connect to the database and the model is not to be changed regarding general table structure of the other entities.

What I tried

  1. I tried using the Hibernate Inheritance strategy with Table per Class, whereas User, Employee and Department are subclassed from a new AbstractEntity, sharing ID and Name property from parent class. So User, Employee and Department still have their own tables. I can now map Report <-> AbstractEntity and this works. BUT: As one can expect, this causes heavy performance problems when there are more than about 20 reports or so, as Hibernate internally has to do heavy joining on all subclass tables.

  2. Single Table per Hierarchy is not an option, because of change of开发者_JAVA百科 the table structure (see Problem). Additionally, all entities only share ID and Name as common properties.

Possible Solution

One possible solution would be to implement the mapping by myself. That is, I store Id and entity class in Report. The getter for AbstractEntity could now decide based on the saved values from which table to load and return the correct entity.

But: Problem here is, I cannot do session stuff in the Entity Class, as the session is not known to the Report class. Also, this would mix up logic and model layer.

Workaround would be to write some kind of wrapper in the DAO, where the correct entity is loaded from the database and injected into the result. But this is very error prone, as every DAO method has to be overridden.

Question

So my question is: Is there a way to somehow catch or intercept the retrieval of the Report Entity from the database and inject loading of the correct AbstractEntity there?

Or is there another, more elegant way to do what I want (must be ;))?

I'm using Hibernate 3.6 using Annotations without EntityManager in a Java EE Environment with DAOs as in http://community.jboss.org/wiki/GenericDataAccessObjects.


I'd take the opposite approach, in that I'd map the Report as a table per class hierarchy, and add a discriminator column to determine if it's an Employee, Group, or Department report.

0

精彩评论

暂无评论...
验证码 换一张
取 消