Created
May 6, 2024 11:33
-
-
Save rcaneppele/be85c6b495fa8b5b2847dd920d7bb0a2 to your computer and use it in GitHub Desktop.
Mapeamento ManyToMany com JPA
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Entity | |
@Table(name = "estudantes") | |
public class Estudante { | |
@Id | |
@GeneratedValue(strategy = GenerationType.IDENTITY) | |
private Long id; | |
private String nome; | |
//outros atributos... | |
@ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}) | |
@JoinTable(name = "matriculas", | |
joinColumns = @JoinColumn(name = "estudante_id"), | |
inverseJoinColumns = @JoinColumn(name = "turma_id") | |
) | |
private Set<Turma> matriculas = new HashSet<>(); | |
public void registrarMatricula(Turma turma) { | |
matriculas.add(turma); | |
turma.getMatriculas().add(this); | |
} | |
public void removerMatricula(Turma turma) { | |
matriculas.remove(turma); | |
turma.getMatriculas().remove(this); | |
} | |
//getters, setters, equals, hashCode, etc. | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Entity | |
@Table(name = "turmas") | |
public class Turma { | |
@Id | |
@GeneratedValue(strategy = GenerationType.IDENTITY) | |
private Long id; | |
private String codigo; | |
//outros atributos... | |
@ManyToMany(mappedBy = "matriculas") | |
private Set<Estudante> matriculas = new HashSet<>(); | |
//getters, setters, equals, hashCode, etc. | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment