FernandoPaiva
FernandoPaiva

Reputation: 4460

How can I join 3 entities JPA?

I have 3 entities: Aluno, Turma and Modalidade. Now I need create Matricula, this entity Matricula will contain all ids of Aluno, Turma and Modalidade with others attribute.

one Matricula can have one Aluno and can have many Turma and can have many Modalidade.

Entity Matricula, can have: OneToOne Aluno OneToMany Turma OneToMany Modalidade

I hope can yours understand.

How to I do that ?

Upvotes: 2

Views: 707

Answers (1)

JamesENL
JamesENL

Reputation: 6540

I have a tutorial that goes into a fair bit of detail about how you set up various relationships using Hibernate annotations. You can find it here.

I'm going to assume that you'd want bi-directional relationships using a foreign key mapping (as shown in the tutorial, if this is wrong, you can find the uni-directional configurations there), you can basically just declare your classes like this:

@Entity
@Table
public class Matricula {

    @Id
    private long matriculaId;

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "alunoId")
    private Aluno aluno;

    @OneToMany(mappedBy="turma")
    private List<Turma> turmas;

    @OneToMany(mappedBy="modalidade")
    private List<Modalidade> modalidades;
}

@Entity
@Table
public class Turma {
    //Put a unique ID here to be used as PK

    @ManyToOne
    @JoinColumn(name="matriculaId)
    private Matricula matricula;
}

@Entity
@Table
public class Modalidade {

    //Put a unique ID here to be used as PK

    @ManyToOne
    @JoinColumn(name="matriculaId)
    private Matricula matricula;
}

@Entity
@Table
public class Aluno {

    //Put a unique ID here to be used as PK

    @OneToOne(mappedBy="aluno")
    private Matricula matricula;
}

Please note that this is assuming that your column names will match, and that your database is correctly set up.

Hope it goes well

Upvotes: 1

Related Questions