TheDeveloper
TheDeveloper

Reputation: 13

Hibernate One To Many Mapping With Fixed Values

I don't have a lot of experience with database design and i try to understand the general logic behind it with using an ORM like hibernate. I have two tables user and languages. User could know one or more languages so there is a one to many relation between two tables. But i have a fixed length of languages English , Spanish and French for example. As i understand with each new user instance persisted there will be duplicate entries in the language table with a foreign key of that person. Is there a way to prevent this duplicate entries ?

Upvotes: 1

Views: 484

Answers (1)

K.Nicholas
K.Nicholas

Reputation: 11561

Your understanding is a little confused. You can map a OneToMany relationship using a Foreign Key, and there are good database reasons to do so, though generally a JPA provider recommends against it. However, you are describing a ManyToMany relationship. A User will (or could) have many Languages. A Language will have many Users. When you create a many to many relationship with annotations:

@Entity
public class Person {
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    @ManyToMany
    private List<Language> languages;

and

@Entity
public class Language {
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

The JPA provider will create an association or Join Table, with an id from each Entity in it:

create table Person_Language (Person_id bigint not null, languages_id bigint not null)

When you create a language, an entry will be put in the language table. When you create a user, an entry will be put into the user table. When you add a language to a person's languages then an entry will be put into the Join Table.

insert into Person_Language (Person_id, languages_id) values (?, ?)

There will be only unique combinations of Person_id and languages_id in the join table, and so the database will be well normalized. You would not be able to assign a language to multiple users using a Foreign Key in the Language entity for the reason you pointed out: there would be only one foreign key column for any given language.

Upvotes: 1

Related Questions