2

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 ?

FernandoPaiva
  • 4,410
  • 13
  • 59
  • 118

1 Answers1

1

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

Community
  • 1
  • 1
JamesENL
  • 6,400
  • 6
  • 39
  • 64
  • thanks for your attention! If I use `mappedBy` in `@OneToMany` at Matricula all id Turma and Modalidade isn't contained in Matricula table of database, that's it ? I want that all ids stay contained at table Matricula. Its possible or not ? – FernandoPaiva Aug 12 '14 at 04:41
  • No, you can't have the primary key for a table contained within another table. The primary key for each object/table should be contained within that table. – JamesENL Aug 12 '14 at 04:42
  • I mean, yes it's possible to store primary key's for tables in another table, but you should never do it. It defeats the entire point of having a Primary Key on the database table – JamesENL Aug 12 '14 at 04:53