Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a ManyToOne relationship between two abstract classes

Tags:

hibernate

I have 4 classes as below...

@MappedSuperclass
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class Platform{

    @Id
    @Column(name = "PLATFORM_ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer platformId;

    ...


@Entity
@Table(name = "ANDROID_PLATFORM")
public class AndroidPlatform extends Platform{

    public AndroidPlatform(){

    }
    ...


@MappedSuperclass
@Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)
public abstract class Application{

    @Id
    @Column(name = "APPLICATION_ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer applicationId;

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="PLATFORM_ID")
    private Platform platform;

    ...


@Entity
@Table(name = "ANDROID_APPLICATION")
public class AndroidApplication extends Application {
    public AndroidApplication(){

    }
    ...

When i started my project it throws an error like this

org.hibernate.AnnotationException: @OneToOne or @ManyToOne on com.***.model.AndroidApplication.platform references an unknown entity: com.***.model.Platform
...

What is wrong in my classes or what is the best approach for using abstract classes in hibernate ?

Please help.

like image 541
Ercan Celik Avatar asked Dec 28 '25 21:12

Ercan Celik


1 Answers

In your abstract class Application (and by inheritance in AndroidApplication) you are using private Platform platform;. Platform is an abstract class which can't be instanciated and which has only partial mapping information (the concrete table name is missing).

Hibernate needs a parameterless constructor for instanciating loaded entities. Also it needs to know which class to use (not the abstract but the implementing class) and it needs all mapping information by the type of the member variable.

Solution: You have to exchange private Platform platform with private AndroidPlatform platform, either in Application or in AndroidApplication, and this variable of type AndroidPlatform must have the hibernate annotations.

2nd solution: If you absolutely need the Java structure as it is then you can use xml mapping files. There you have the possibility to specify the exact type in each subclass, even if the Java class for the member variable is a superclass of that type.

like image 179
Johanna Avatar answered Dec 31 '25 13:12

Johanna