Using xml with hibernate sucks!!! Why dont you try annotations.
If you have a N:N relationship between two tables, you have to create another table (associative table). The same applies to Persistent classes (annotated or via XML), you have to create an associative persistent class.
A composite key is an attribute compound of more than one value, this means that the pair of values that compose the PK must be unique in the table, right?
Thats why you have to create a class to represents the composite primary key. Then you have to code the equals and hashcode methods.
*----------------------------------------------------------------------------------*
This example is composed of two entities(persistent classes):
-Curso
-Disciplina
With the following Relationship:
Curso * * Disciplina
Of course another table is required, I concatenated the names of the involved tables:
CursoDisciplina
But there is a restriction:
One course cant be related to the same disciplina more than one time (the same applies to disciplina).
The solution:
Use the entities attributes as a compound PK in the associative table
This is an example of a composite PK class:
@Embeddable
public class ChaveComposta implements java.io.Serializable {
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="id_curso")
private Curso curso;
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="id_disciplina")
private Disciplina disciplina;
/** Creates a new instance of ChaveComposta */
public ChaveComposta() {
}
public Curso getCurso() {
return curso;
}
public void setCurso(Curso curso) {
this.curso = curso;
}
public Disciplina getDisciplina() {
return disciplina;
}
public void setDisciplina(Disciplina disciplina) {
this.disciplina = disciplina;
}
}
and here an associative entity(class) that establishes a relation between two other entities(classes).@Entity
@Table(name="curso_disciplina")
public class CursoDisciplina implements java.io.Serializable {
@EmbeddedId
private ChaveComposta chaveComposta;
@Column(name="dataAssociacao")
@Temporal(TemporalType.DATE)
private Calendar dataAssociacao;
/** Creates a new instance of CursoDisciplina */
public CursoDisciplina() {
}
public ChaveComposta getChaveComposta() {
return chaveComposta;
}
public void setChaveComposta(ChaveComposta chaveComposta) {
this.chaveComposta = chaveComposta;
}
public Calendar getDataAssociacao() {
return dataAssociacao;
}
public void setDataAssociacao(Calendar dataAssociacao) {
this.dataAssociacao = dataAssociacao;
}
}
This is just a snippet I have the project (Netbeans 5.5) here.
Email me:
charlles.cuba@gmail.com