Andrey
Andrey

Reputation: 23

How i can map two classes to one field

What we have? We have two subclases from Dictionary and QueueProfile. I want map field profile like in code below. How i can map this?

@MappedSuperclass
public class Dictionary implements Serializable {}

@Entity
public class Speciality extends Dictionary{}

@Entity
public class LdpType extends Dictionary{}

@Entity
public class QueueProfile{
    Dictionary profile;
}

Or it's not posible in this case. I know that i can create two implementations of QueueProfile with diferent fields and discrimination, but its not so elegant

Upvotes: 0

Views: 69

Answers (1)

Stuart Caie
Stuart Caie

Reputation: 2913

The answer depends on which way round you want to store it. When using @MappedSuperclass, it expects that you're going to share one superclass, but it's clear from the entity itself which table to get data from. For example:

@MappedSuperclass
public class Dictionary implements Serializable {}
@Entity
public class QueueProfileUsingSpeciality extends Dictionary {}
@Entity
public class QueueProfileUsingLdpType extends Dictionary {}

It sounds like you actually want something that could either be Speciality or LdpType, in the QueueProfile entity. In which case, Hibernate knows where to get data for QueueProfile, but to instantiate profile it needs to know which table/entity/subclass to use. This is handled by using a discriminator.

public class Dictionary implements Serializable {}
@Entity
@DiscriminatorValue("Foo")
public class Speciality extends Dictionary{}
@Entity
@DiscriminatorValue("ldp_type_profile")
public class LdpType extends Dictionary{}
@Entity
@Inheritance
@DiscriminatorColumn(name="which_profile")
public class QueueProfile {
    Dictionary profile;
}

Upvotes: 1

Related Questions