Spring Data JPA Establish a joint primary key for a table

  • 2021-07-18 08:03:37
  • OfStack

Recently, I encountered a small problem, that is, how to use Spring Data JPA to establish the joint primary key of the table? Then we explored the following two ways.

Mode 1:

The first way is to annotate both fields directly above the class property with @ Id, as follows, adding the joint primary key to the fields stuNo and stuName:


@Entity
@Table(name = "student")
public class Student {

  @Id
  @Column(name = "stu_no", nullable = false, length = 11)
  private Integer stuNo;

  @Id
  @Column(name = "stu_name", nullable = false, length = 128)
  private String stuName;

  @Column(name = "stu_age", nullable = false, length = 3)
  private Integer stuAge;

  @Column(name = "class_id", nullable = false, length = 8)
  private String classId;
}

Just note that entity classes need to implement the Serializable interface.

This method is not very good, although you can successfully create the table, but when using JpaRepository, you need to specify the type of primary key ID, which will report an error, so it is better to use the second method.

The second way:

It is also very simple to implement. We need to create a new class, or establish a joint primary key with stuNo and stuName. This class needs to implement Serializable interface.


public class StudentUPK implements Serializable {

  private Integer stuNo;

  private String stuName;

}

Then add the @ IdClass annotation to the entity class Student, and still add the @ Id annotation to the two fields:


@Entity
@IdClass(StudentUPK.class)
@Table(name = "student")
public class Student {

  @Id
  @Column(name = "stu_no", nullable = false, length = 11)
  private Integer stuNo;

  @Id
  @Column(name = "stu_name", nullable = false, length = 128)
  private String stuName;

  @Column(name = "stu_age", nullable = false, length = 3)
  private Integer stuAge;

  @Column(name = "class_id", nullable = false, length = 8)
  private String classId;
}

This creates the table successfully, and when using JpaRepoistory, you can specify the primary key as the StudentUPK class, like this: public interface StudentRepository extends JpaRepository < Student, StudentUPK > .


Related articles: