I'm starting to study Hibernate and would like to know how to save a foreign key entity. Here is an example of two entities:
Student:
@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 that contains a 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 (not put to not get too long)
I would like to know what the "save" method would look like for enrollment. Thank you in advance!