0

Given the following scenario:

  • A project using a framework
  • The framework defines basic entity classes (used for logging, user management etc.)
  • The project has application specific entity classes.

I want to subclass a framework class in a way that does not need changes to the framework code nor the framework specific database schema (apart from any constraints that maybe introduced by additional mappings).

Here is a simplified framework class:

package com.example.parent;

@Entity
@Table("entities")
public class ExampleEntity {

    @Id
    @GeneratedValue
    protected Integer id;

    protected String name;

}

And the application specific extension:

package com.example.child;

@Entity
public class ExampleEntity extends com.example.parent.ExampleEntity {

    @OneToMany
    @JoinColumn
    protected Set<OtherEntity> otherEntities;    

}

As you can see this just adds an additional mapping to an application specific entity class. This won't work with Hibernate 4.3.11 out-of-the-box. It will try to create a discriminator column (dtype) which is not desired and IMHO not required here.

I want this to be as transparent as possible (i.e. without changing anything on the framework side) and without any additional manual mapping/casting in the application. Effectively, I want to trick Hibernate into loading only instances of com.example.child.ExampleEntity without the framework even noticing.

TL;DR

How to trick Hibernate into loading entities from the entities table as instances of com.example.child.ExampleEntity?

Koraktor
  • 41,357
  • 10
  • 69
  • 99

1 Answers1

0

You can used @Inheritance(strategy = InheritanceType.JOINED) on the parent class. You can find an example here.

So it would work with

package com.example.parent;

@Entity
@Table("entities")
@Inheritance(strategy = InheritanceType.JOINED)
public class ExampleEntity {

    @Id
    @GeneratedValue
    protected Integer id;

    protected String name;

}

So you can join any other table to children or parent

This is the official documentation about inheritance mapping.

Korthez
  • 11
  • 4
  • I think the origional question said how to get it to work _without_ changing the framework classes, but I think you are suggesting to modify the framework class by adding the @Inheritance annotation. – Chris Knoll Mar 10 '17 at 07:23