Skip to content

Instantly share code, notes, and snippets.

@yabetancourt
Created October 9, 2022 22:42
Show Gist options
  • Save yabetancourt/ee3542380a758aea829e361082bf5789 to your computer and use it in GitHub Desktop.
Save yabetancourt/ee3542380a758aea829e361082bf5789 to your computer and use it in GitHub Desktop.
Creacion de una clase para una relacion M:M con el id embebido. Observar como queda el repositorio.
@Entity
public class CourseEnrollment {
@EmbeddedId
protected Id id = new Id();
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "student_id", insertable = false, updatable = false)
protected Student student;
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "edition_id", insertable = false, updatable = false)
protected CourseEdition edition;
@Column(nullable = false)
protected Boolean isDropped;
@ManyToOne(fetch = FetchType.LAZY)
protected Evaluation evaluation;
public CourseEnrollment() {
}
public CourseEnrollment(Student student, CourseEdition edition) {
this(student, edition, false, null);
}
public CourseEnrollment(Student student, CourseEdition edition, Boolean isDropped, Evaluation evaluation) {
this.id.editionId = edition.getId();
this.id.studentId = student.getId();
this.student = student;
this.edition = edition;
this.isDropped = isDropped;
this.evaluation = evaluation;
}
//getters and setters
@Embeddable
public static class Id implements Serializable {
@Column(name = "student_id")
protected Long studentId;
@Column(name = "edition_id")
protected Long editionId;
public Id() {
}
public Id(Long studentId, Long editionId) {
this.studentId = studentId;
this.editionId = editionId;
}
public boolean equals(Object o) {
if (o instanceof Id that) {
return this.studentId.equals(that.studentId)
&& this.editionId.equals(that.editionId);
}
return false;
}
public int hashCode() {
return studentId.hashCode() + editionId.hashCode();
}
}
}
public interface CourseEnrollmentRepository extends JpaRepository<CourseEnrollment, CourseEnrollment.Id> {
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment