Ernio
Ernio

Reputation: 978

Is it possible to represent Entity's field Map<Enum, Entity> in JPA with just 2 tables?

Given:

    enum Language
    {
        EN
        DE
        IT
        FR
    }

    @Entity
    @Table(name = "translation")
    class Translation
    {
        Long entry_id; // mapped to Entry
        Language language; // creates primary key with entry_id
        String content;

        // more fields ...
    }

    @Entity
    @Table(name = "entry")
    class Entry
    {
        Long id;
        Map<Language, Translation> translations;

        // more fields ...
    }
  1. Does JPA 3.1 and Hibernate 6.1.5+ allow to represent above in relational database (MySQL) with just 2 tables, such as:
    table entry (id, stuff)
    table translation (entry_id, language, content) primary key [entry_id, language]
  1. Also consider extension to above problem, where content is another @ManyToOne relation:
    @Entity
    @Table(name = "translation")
    class Translation
    {
        Long entry_id; // mapped to Entry
        Language language; // creates primary key with entry_id
        List<Post> posts;
    }
    
    @Entity
    @Table(name = "post")
    class Post
    {
        Long id;
        String content;
    }

How would one approach this in order to have most of all worlds:

Upvotes: 0

Views: 56

Answers (1)

Christian Beikov
Christian Beikov

Reputation: 16452

Easy peasy:

enum Language
{
    EN
    DE
    IT
    FR
}

@Embeddable
class Translation
{
    String content;

    // more fields ...
}

@Entity
@Table(name = "entry")
class Entry
{
    Long id;
    @ElementCollection
    @CollectionTable(name = "translation")
    @MapKeyEnumerated(EnumType.STRING)
    @MapKeyColumn(name = "language")
    Map<Language, Translation> translations;

    // more fields ...
}

Upvotes: 1

Related Questions