SoFunction
Updated on 2025-03-08

SpringDataJPA entity class relationship mapping configuration method

SpringDataJPA

//: Lazy loading. When loading an entity, the properties that define lazy loading will not be loaded from the database immediately.//: Emergency loading. When an entity is loaded, the attributes that define emergency loading will be loaded from the database immediately.//cascade = means that the associated operation is performed in all cases, i.e. save-update and delete@JsonBackReference   //Solve the problem of circular reference@JsonIgnoreProperties(value = "order") //Solve the problem of circular reference, the order content is large and not loaded//Bidirectional mapping existsjsonUnlimited recursion problem Need annotations to handle Recommended to use the second note valueThe value is the variable value that maps the other party's table

1. One-way one-to-one mapping

One party

  //teacher  @Id @GeneratedValue(strategy=)
  private int id;
  private String name;
  private long salary;
  @OneToOne 
  @JoinColumn(name="PSPACE_ID") 
  private ParkingSpace parkingSpace;

One party

    //PARKING LOT    @Id @GeneratedValue(strategy=)
    private int id;
    private int lot;
    private String location;

Summarize

When adding, you need to add the @OneToOne first, and delete it too.

2. Two-way one-to-one mapping

One party

  //personnel  @Id
  @GeneratedValue(strategy=)
  private long id;
  private String name;
  @OneToOne
  @JoinColumn(name="DEPT_ID")
  @JsonIgnoreProperties(value = "person")
  private Department department;

One party

  //department  @Id
  @GeneratedValue(strategy=)
  private long id;
  private String name;
  @OneToOne(mappedBy="department")
  @JsonIgnoreProperties(value = "department")
  private Person person;

Summarize

@JsonBackReference   //Solve the problem of circular reference@JsonIgnoreProperties(value = "order") //Solve the problem of circular reference, the order content is large and not loaded//Bidirectional mapping existsjsonUnlimited recursion problem Need annotations to handle Recommended to use the second note valueThe value is the variable value that maps the other party's table

3. One-way one-to-many mapping

One party

    @Id
    @GeneratedValue
    private Long id;
    @Column(length = 32)
    private String name;
    @OneToMany(cascade = , fetch = )//Cascade save, update, delete, refresh; delay loading    @JoinColumn(name = "author_id")//Add a foreign key column to the book table to achieve one-to-many one-way association    private Set<Book> books = new HashSet<Book>();

Multiple

    //In the case of one-way one-to-many, multiple parties do not need to add any association marks. @Id
    @GeneratedValue
    private Long id;
    @Column(length=32)
    private String name;

Summarize

Because it is a one-way relationship, multiple parties do not need to add any association logos.

4. Two-way one-to-many mapping

One party

    @Id
    @GeneratedValue(strategy = )
    private Integer id; //Primary key    private String name; //Name    //Description Customers can have multiple orders    @OneToMany(mappedBy = "customer", cascade = )
    @JsonBackReference
    private Set<Order> order = new HashSet<Order>();

Multiple

    @Id
    @GeneratedValue(strategy = )
    private Integer id;
    private Double money;
    private String receiverInfo; //Received Address    // Orders are associated with customers    @ManyToOne(cascade = )
    @JoinColumn(name = "c_id") //Specify foreign key column    @JsonIgnoreProperties(value = "order") //Solve the problem of circular reference, the order content is large and not loaded    private Customer customer; //Describe the order belongs to a certain customer

Summarize

@JsonBackReference   //Solve the problem of circular reference@JsonIgnoreProperties(value = "order") //Solve the problem of circular reference, the order content is large and not loaded//There is a problem of JSON infinite recursion in the bidirectional mapping. Annotations are required to deal with it. It is recommended to use the second annotation value value to map the variable value of the other party's table.

5. One-way many-to-one mapping

Multiple

 @GeneratedValue
 @Id
 private Integer id;
 @Column(name="ORDER_NAME")
 private String orderName;
 // Map the association relationship of one-way n-1 //Use @ManyToOne to map many-to-one relationships //Use @JoinColumn to map foreign keys //You can use the fetch attribute of @ManyToOne to modify the loading policy of the default associated attribute @JoinColumn(name="CUSTOMER_ID")  //The external key is the primary key of one side @ManyToOne(fetch=)
 private Customer customer;

One party

    //In the case of one-way many-to-one, one party does not need to add any association identifier    @GeneratedValue(strategy=)
    @Id
    private Integer id;
    private String lastName;
    private String email;
    private int age;
    private Date createdTime;
    private Date birth;

Summarize

When saving many to one, it is recommended to save one end of 1 first and then one end of n so that there will be no additional update statements.

6. Two-way many-to-one mapping

Multiple

 @GeneratedValue
 @Id
 private Integer id;
 @Column(name="ORDER_NAME")
 private String orderName;
 // Map the association relationship of one-way n-1 //Use @ManyToOne to map many-to-one relationships //Use @JoinColumn to map foreign keys //You can use the fetch attribute of @ManyToOne to modify the loading policy of the default associated attribute @JoinColumn(name="CUSTOMER_ID")
 @ManyToOne(fetch=)
 @JsonIgnoreProperties(value = {"customer","orders"})
 private Customer customer;

One party

    @GeneratedValue(strategy=)
    @Id
    private Integer id;
    @Column(name="LAST_NAME",length=50,nullable=false)
    private String lastName;
    private String email;
    private int age;
    //Define date format    @Temporal()
    private Date createdTime;
    @Temporal()
    private Date birth;
    // Map the relationship between 1-n in one-way    // Use @OneToMany to map 1-n associations    //Use @JoinColumn to map the name of a foreign key    //You can use the fetch attribute of @OneToMany to modify the loading policy    //You can use the @OneToMany's cascade property to modify the default deletion policy//    @JoinColumn(name="CUSTOMER_ID")
    //One end gives up maintaining relationship    @OneToMany(fetch=,cascade={},mappedBy="customer")
    @JsonIgnoreProperties(value = "orders")
    private Set<Order> orders = new HashSet<>();

Summarize

1. Must use @JsonIgnoreProperties annotation to intercept the problem of infinite recursion when converting json

2. If it is a two-way 1-n relationship, when executing the save:

(1) If you save one end of n first and then one end of 1, by default, there will be 2n additional UPDATE statements;

(2) If you save one end of 1 first, n UPDATE statements will appear.

(3) Therefore, when performing a two-way 1-n relationship, it is recommended to use the n party to maintain the relationship, while the 1 party does not maintain the relationship, which will effectively reduce the SQL statement (that is, the table corresponding to one end of N is used to associate the one end of 1, and the table primary key of the foreign key corresponds to the one end of 1)

Note: If the mappedBy attribute is used in @OneToMany on one end of 1, the @OneToMany cannot use the @JoinColumn attribute.

7. One-way many-to-many mapping

Multiple

   @Id
    @GeneratedValue
    private Long id;
    private String name;
    // means many to many    @ManyToMany(cascade = )
    // The table name of the intermediate table    @JoinTable(name = "t_user_role", joinColumns = {@JoinColumn(name = "user_id")},
            //The reverse side of the user table is role            inverseJoinColumns = {@JoinColumn(name = "role_id")})
    private Set<Role> roles = new HashSet<>();

Multiple

    @Id
    @GeneratedValue
    private Long id;
    private String name;

Summarize

use@JoinTableTo map intermediate tables

1. name Name pointing to the middle table

2. joinColumns Map the foreign keys in the intermediate table where the current class resides

2.1 nameSpecify the column name of the foreign key column

2.2 referencedColumnNameSpecify which column of the current table is associated with the foreign key column

3. inverseJoinColumns Map the foreign keys of the intermediate table where the associated class is located

8. Bidirectional many-to-many mapping

Multiple

    @Id
    @GeneratedValue
    private Long id;
    private String name;
    // means many to many    @ManyToMany(fetch = ,cascade = )
    @JoinTable(name="t_user_role",joinColumns={@JoinColumn(name="user_id")},
            inverseJoinColumns ={@JoinColumn(name="role_id")} )
    @JsonIgnoreProperties(value = "users")
    private Set<Role> roles = new HashSet<>()

Multiple

    @Id
    @GeneratedValue
    private Long id;
    private String name;
    @ManyToMany(fetch = ,cascade = )
    @JoinTable(name="t_user_role",joinColumns={@JoinColumn(name="role_id")},
            inverseJoinColumns ={@JoinColumn(name="user_id")} )
    @JsonIgnoreProperties(value = "roles")
    private Set<User> users = new HashSet<>();

Summarize

use@JoinTableTo map intermediate tables

1. nameName pointing to the middle table

2. joinColumnsMap the foreign keys in the intermediate table where the current class resides

2.1 nameSpecify the column name of the foreign key column

2.2 referencedColumnNameSpecify which column of the current table is associated with the foreign key column

3. inverseJoinColumnsMap the foreign keys of the intermediate table where the associated class is located

@JsonBackReference //Solve the problem of circular reference@JsonIgnoreProperties(value = "order") //Solve the problem of circular reference, the order content is large and not loaded

There is a problem of JSON infinite recursion in bidirectional mapping. Annotations are required to deal with it. It is recommended to use the second annotation value value to map the variable value of the other party's table.

The above is personal experience. I hope you can give you a reference and I hope you can support me more.