rygel
rygel

Reputation: 43

Hibernate and inheritance

I have two tables Text and inhereted TextUser.

Text contains: id, textType
TextUser contains: id, locale, name, title

TextUser.id is foreign key to Text.id. So example of join will be:

Text.id - Text.textType - TextUser.id - TextUser.locale - TextUser.name

100          1            100          en            name1
100          1            100          fr            name2
101          1            101          en            name3

So having key 100 we have one record in Text and two records with the same id but different locales (en, fr) in TextUser.

It's a legacy system so i can't modify the structure. Now I'm trying to process it with hibernate.

@Entity(name = "Text")
@Inheritance(strategy = InheritanceType.JOINED)
public abstract class Text {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "TextId")
    private Long id;

    @Column(name = "TextType")
    private Integer textType;

and

    @Entity
    @Table(name = "TextUser")
    @ForeignKey(name = "FK_TextUser_Text")
    public class TextUser extends Text {
    
        @Column(name = "locale")
        private String locale;
    
        @Column(name = "name")
        private String name;

So it works perfectly for one locale. But how can I insert new value with key 100, but new locale? We have ID in Text and hibernate uses it for foreign key TextUser.id. So if I set explicitly id but different locale I will get "org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session"

Upvotes: 1

Views: 387

Answers (2)

axtavt
axtavt

Reputation: 242686

It's not a valid case for inheritance.

You should model it as a composite key (TextUser has a composite key (id,locale), right?) and many-to-one realtionship with derived identity (since composite key of TextUser contains a foreign key).

One of the possible approaches is shown in @MapsId javadoc.

Upvotes: 1

Augusto
Augusto

Reputation: 29897

You won't be able to map those classes with an inheritance relationship, as the IDs on the parent table will be duplicated (that's the error you're getting at the moment).

You'll need to map the two classes a one-to-many relationship (which they are). The Text class will remain as it's (except for the @Inheritance) and the UserText will have a composite id between UserText.id and UserText.locale.

If you don't need to update those tables, you can create a view with the join of both tables (Text.id - Text.textType - TextUser.locale - TextUser.name) and use the composite id: Text.id and TextUser.locale.

Upvotes: 0

Related Questions