bovae
bovae

Reputation: 331

Hibernate @SecondaryTable - Specifying foreign key of primary table

I have two tables:

  1. language

    CREATE TABLE language (
      id   BIGSERIAL,
      name TEXT NOT NULL UNIQUE,
      PRIMARY KEY (id)
    );
    
  2. translation

    CREATE TABLE translation (
      id                BIGSERIAL,
      language_id       BIGINT REFERENCES language (id),
      translation_key   TEXT NOT NULL,
      translation_value TEXT NOT NULL,
      PRIMARY KEY (id)
    );
    

    And I would like to get such entity, where translation table (primary table) joins language table by language_id from primary table. Problem: at the moment it joins by translation PK(id).

    @Entity
    @Table(name = "translation")
    @SecondaryTable(name = "language", pkJoinColumns = @PrimaryKeyJoinColumn(name = "id"))
    public class Translation {
    
        @Id
        @Column(name = "id")
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private long id;
    
        @Column(table = "language", name = "name")
        // ON translation.language_id = language.id
        private String language;
    
        @Column(name = "translation_key")
        private String translationKey;
    
        @Column(name = "translation_value")
        private String translationValue;
    
        // getters and setters
    }
    

    Where I should specify it in my code to do it correctly? SQL example: SELECT t.id, l.name, translation_key, translation_value FROM translation t INNER JOIN language l on t.language_id = l.id;

Upvotes: 1

Views: 4064

Answers (2)

Rami Alazzawi
Rami Alazzawi

Reputation: 1

@SecondaryTable(name = "language")

this way it is going to generate value for the translation id and insert it to the language foreign key automatically if you specify pkJoinColumn it is going to relate the tables through the primary key while if you don't mention that, it would do it through the foreign key. After that you need to create a trigger and sequence for the language table id column. It should work.

Upvotes: 0

crizzis
crizzis

Reputation: 10716

You cannot use @SecondaryTable for the purpose you describe.

@SecondaryTable is used when a single entity is spread across multiple tables. Each of these 'pieces' of the entity must be privately owned by the entity, and is in a one-to-one relation with every other 'piece'.

If you want a many-to-one relation between translations and languages, you need to use @ManyToOne (and create a separate Language entity) instead.

Upvotes: 1

Related Questions