java – PrimaryKey, ForeignKey and Unique With JPA

Question:

I have the following situation:

  1. Student Entity (id and others)
  2. Evaluation Entity (id and others)
  3. Entity GradeAvaliacaoAluno (evaluationId, studentId)

I want to transform the attributes assessmentId, studentId that have relationships with entities 1 and 2 into PrimaryKey and that are Unique.

What is the best way for this mapping?

I've already checked some forms but be in doubt about how to actually use them.

Answer:

1- First you need to map the Student entity

@Entity
@Table(name="Aluno") // Eu sempre informo o 'name', mania minha
public class Aluno implements Serializable {
  @Id
  @Column(name = "id")
  private java.lang.Long id; 

  // Demais campos...
}

2 – Map Assessment Entity

@Entity
@Table(name="Avaliacao")
public class Avaliacao implements Serializable {
  @Id
  @Column(name = "id")
  private java.lang.Long id; 

  // Demais campos...
}

3 – Map the NotaAvaliacao entity

Before posting the example, it is not always necessary to map these many-to-many. I decided to map it because it has information (which I believe is the student's grade).

@Entity
@Table(name="NotaAvaliacaoAluno")
public class NotaAvaliacaoAluno implements Serializable {
  @Id
  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn( name = "avaliacaoId", referencedColumnName="id")
  private Avaliacao avaliacao; 

  @Id
  @Column(name = "alunoId")
  @JoinColumn(name = "alunoId", referencedColumnName="id")
  private Aluno aluno; 

  // Demais campos...
}

4 – Now we go back to the student class and include

 @OneToMany(fetch=fetchType.LAZY, mappedBy="aluno")
 private List<NotaAvaliacaoAluno> notasValiacaoAlunoList;

Ready.

PS: As I don't know your model, I believe the most appropriate is to analyze my answer, understand what I suggested and adapt it to your case.

Scroll to Top