3
I’m starting to study Hibernate and I’d like to know what the method of saving an entity with a foreign key looks like. The following is an example of two entities:
Pupil:
@Entity(name = "aluno")
public class Aluno extends Pessoa{
@Column(nullable=false)
private String matricula;
@Column(nullable=false)
private String senha;
public Aluno(String nome, String sexo, String dataNascimento,
String matricula, String senha) {
super(nome, sexo, dataNascimento);
this.matricula = matricula;
this.senha = senha;
}
Course:
@Entity(name = "curso")
public class Curso {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@Column(nullable=false)
private String nome;
@Column(nullable=false)
private int duracao;
public Curso(String nome, int duracao) {
this.nome = nome;
this.duracao = duracao;
}
Now the class containing foreign key:
@Entity(name = "matricula")
public class Matricula {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@OneToOne
@JoinColumn(name = "fk_curso",nullable=false)
private Curso curso;
@OneToOne
@JoinColumn(name = "fk_aluno",nullable=false)
private Aluno aluno;
@Column(nullable=false)
private String matricula;
public Matricula(Curso curso, Aluno aluno, String matricula) {
this.curso = curso;
this.aluno = aluno;
this.matricula = matricula;
}
All classes have getters and setters (I didn’t put it in so it wouldn’t get too long)
I would like to know what would be the "save" method for enrollment. Thank you from now!
Thanks, it all worked out. It helped a lot, great explanation
– Leonardo Freitas
Hello @Leonardo. You can indicate that a reply was useful by voting on it. If an answer solved your problem you should also accept it so that other users with the same problem know which solution you have just adopted.
– Anthony Accioly
That of Antonio Edmilson
– Leonardo Freitas