I have a problem with JPA (using Spring and Hibernate) when having 2 tables, one of them represents the translation of the other one. My intention is to retrieve the whole information of the registries in one query, but I can't get it: I need to retrieve first the registry of the TABLE_A, and then the associated registry from TABLE_A_TRANSLATION, and then merge them "by hand". Here is an example:
CREATE TABLE TABLE_A (
ID INTEGER NOT NULL,
CONSTRAINT PK_A PRIMARY KEY (ID)
);
CREATE TABLE TABLE_A_TRANSLATION (
ID INTEGER NOT NULL,
LANG VARCHAR2(2) NOT NULL,
DESCRIPTION VARCHAR2(100) NOT NULL,
CONSTRAINT PK_A_TRA PRIMARY KEY (ID, LANG),
CONSTRAINT FK_A_TRA_A FOREIGN KEY (ID) REFERENCES TABLE_A (ID)
);
The associated JPA Java code, is the following:
@Entity
@Table(name = "table_a")
public class TableA {
@Id
@Column(name = "id", nullable = false, unique = true)
private Integer id;
@Column(name = "code", nullable = false, unique = false, length = 10)
private String code;
private String lang;
private String description;
// getters and setters
}
@Entity
@Table(name = "table_a")
public class TableATranslation {
@Id
@Column(name = "id", nullable = false, unique = true)
private Integer id;
@Id
@Column(name = "lang", nullable = false, unique = true, length = 2)
private String lang;
@Column(name = "description", nullable = false, unique = false, length = 100)
private String description;
// getters and setters
}
And when I want to retrieve a TABLE_A element, I do the following (please, avoid talking about syntactic errors, I know that the 'find' method and the Entity classes are not well described, but it's just an example):
public TableA getOne(Integer id, String lang) {
TableA tableA = entityManager.find(TableA.class, id);
TableATranslation tableATrans = entityManager.find(TableATranslation.class, ...);
tableA.lang = tableATrans.lang;
tableA.description = tableATrans.description;
}
Summarizing, I need to execute 2 requests to the database to have a complete registry. Is it any way to improve it?
Thanks