JPA/HIbernate: Joining 2 Entities Multiple Times
I have a legacy database which can't be changed because it's hooked up to a 3rd party application.
One of the queries I'm working with for a new application looks like the following:
SELECT COL1, COL2, COL3, CODE1, CODE2,
(SELECT CODE_DESC FROM CODETABLE WHERE CODE_TYPE='A' CODE=INCIDENT.CODE1) AS CODE_DESC1,
(SELECT CODE_DESC FROM CODETABLE WHERE CODE_TYPE='B' CODE=INCIDENT.CODE2) AS CODE_DESC2
FROM INCIDENT
WHERE...
I'm trying to figure out how to translate that query into a set of Hibernate entities, but I'm a Hibernate newbie. I have 3 questions:
- How do I join an entity to another entity in a one-to-one relationship multiple times? (the sub-queries)
- How do I join an entity to another entity in a one-to-one relationship using a, for lack of a better word, parameter that has a fixed value (CODE_TYPE='A')?
- Is it possible to do either of the above using annotations (because I like those)?
Here's what I've tried thus far that didn't work:
Object 1:
@Entity
@Table (name="Incident")
public class Incident {
private String col1;
private String col2;
private String col3;
private String code1;
private String code2;
private Code code_desc1;
//private String code_desc2;
/**
* @param code_desc1 the code_desc1 to set
*/
public void setCode_desc1(Code code_desc1) {
this.code_desc1 = code_desc1;
}
/**
* @return the code_desc1
*/
@OneToOne
@JoinTable(name="Codes",
joinColumns=@JoinColumn(name="code1", referencedColumnName="CODE"),
inverseJoinColumns=@JoinColumn(name="CODE_TYPE", referencedColumnName="'A'")
)
public Code getCode_desc1() {
return code_desc1;
}
// Rest of Getters & Setters...
}
Object 2:
@Entity
@Table (name="CODETABLE")
public class Codes {
@Column(name="CODE_DESC")
private String codeDesc;
@Column(name="CODE_TYPE")
开发者_JAVA技巧private String codeType;
@Column(name="CODE")
private String code;
// Getters & Setters
}
Basically, when I run the program, it complains about "A" not being a column name in the Codes entity. Thanks for helping!
You should create a view as the query you described and define an entity mapping to this view.
If you still need the "Code" entity mapped at "Incident", check following example:
@Entity
@Table(name="incident")
public class Incident {
@Id
@Column(name="id")
private Integer id;
@OneToOne
@JoinColumn(name="code1")
private CodeA typeACode;
@OneToOne
@JoinColumn(name="code2")
private CodeB typeBCode;
public Incident() {}
public CodeA getTypeACode() { return this.typeACode; }
public CodeB getTypeBCode() { return this.typeBCode; }
}
The "CodeA" is an entity mapping to a view, which comply with CODE_TYPE='A'. The "CodeB" is same as above recipe.
精彩评论