Skip to content

Instantly share code, notes, and snippets.

@rcaneppele
Created May 6, 2024 11:33
Show Gist options
  • Save rcaneppele/be85c6b495fa8b5b2847dd920d7bb0a2 to your computer and use it in GitHub Desktop.
Save rcaneppele/be85c6b495fa8b5b2847dd920d7bb0a2 to your computer and use it in GitHub Desktop.
Mapeamento ManyToMany com JPA
@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.
}
@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