Pages

Spring JPA Configurations

JPA is used to define relationship among the entity classes in an spring applications. There are different types of requirements and required behaviors among the related tables. In the article below, I am going to discuss a few of those.

Lets say there is a following relationship between records of following tables.


  • Table A is the parent entity and can have multiple B entities
  • Table A has one C entity
  • Table A points to one D entity
  • C cannot exist without corresponding A
  • B's cannot exist without A
  • D can exist independently 

@Entity
@Table(name="A")
class A{

          @Id
          @GeneratedValue(strategy = GenerationType.IDENTITY)
          private Long id;

          private String otherAProperties;

          // this reverse maps B to A, if A is deleted, B will also be deleted
          // aEntity is the field name in B class
          @OneToMany(mappedBy = "aEntity",
                cascade = CascadeType.ALL)
          private List<B> bs;

          // this reverse maps C to A, if A is deleted, B will also be deleted
          // aEntity is the field name in C class
          @OneToOne(mappedBy = "aEntity",
                cascade = CascadeType.ALL)
          private C c;

          // this just joins to d, but donot delete d when A is deleted
          @OneToOne
          @JoinColumn(
            name="dId"
          )
          private D d;

}

@Entity
@Table(name="B")
class B{

          @Id
          @GeneratedValue(strategy = GenerationType.IDENTITY)
          private Long id;

          private String otherBProperties;

          // this will cause a field aId to be created in B table which is foreign key to A
          @OneToOne(fetch = FetchType.LAZY)
          @JoinColumn(
            name = "aId",
            nullable = false,
            foreignKey = @ForeignKey(name = "FK_B_A"))
          private A aEntity;

}
@Entity
@Table(name="C")
class C{

          @Id
          @GeneratedValue(strategy = GenerationType.IDENTITY)
          private Long id;

          private String otherCProperties;

          @OneToOne(fetch = FetchType.LAZY)
          @JoinColumn(
            name = "aId",
            nullable = false,
            foreignKey = @ForeignKey(name = "FK_C_A"))
          private A aEntity;

}

@Entity
@Table(name="D")
class D{
         // D does not know about other tables that are referring to it
         // so no mapping to other table necessary

          @Id
          @GeneratedValue(strategy = GenerationType.IDENTITY)
          private Long id;

          private String otherDProperties;
}