Mapping Linking Table with 3 PK's in Hibernate
right now I'm having trouble mapping a linking table with Hibernate.
First of all I want to explain what I want to map: I have 3 tables: Product , DocumentType, Language.
One Product can have each DocumentType (at the moment we have 7 DocumentTypes) in each specific Language (at the moment we have 3 Languages)
That means product "1" can have DocumentType "A" in language "EN", "ES" and "FR".
I created a linking table with 3 foreign keys which are also composite primary key.
Here is how my sql looks like.
CREATE TABLE Person(
id int PRIMARY KEY AUTO_INCREMENT,
name varchar(255)
);
CREATE TABLE DocumentType(
id int PRIMARY KEY AUTO_INCREMENT,
name varchar(255),
key varchar(255)
);
CREATE TABLE Language(
id int PRIMARY KEY AUTO_INCREMENT,
name varchar(255),
code varchar(2)
);
CREATE TABLE Person_DocumentType_Language(
person_id int NOT NULL,
doc_id int NOT NULL,
lang_id NOT NULL,
FOREIGN KEY(person_id)
REFERENCES Person(id),
FOREIGN KEY(doc_id)
REFERENCES DocumentType(id),
FOREIGN KEY(lang_id)
REFERENCES Language(id),
PRIMARY KEY(person_id, doc_id, lang_id)
);
With the last linking table I could tell which Person ha开发者_运维问答s which DocumentTypes and in which Languages. I'm mostly interested in the information which DocumentType has which Language for one Person.
Say I'm Person A. Now I want to know which DocumentTypes I have with which Languages. In SQL it would look like this I think:
Select doc_id, lang_id from Person_DocumentType_Language where person_id=1
Does that make sense? And how could I map this in Hibernate?
One approach is have a Map
from DocumentType
to Language
. I'm a bit rusty on the exact annotation, but here is a start:
public class Person {
@Id
public int id;
@OneToMany(targetEntity=Language.class)
@MapKeyClass(Integer.class)
@CollectionTable(name="Person_DocumentType_Language")
@MapKeyColumn(name="doc_id")
public Map<DocumentType,Language> docTypeLang;
}
精彩评论