Spring boot data JPA database mapping relationship

when using the mapping relationship, we can associate the two tables by setting the association relationship between the master table or the slave table. When querying or doing other operations, we only need to query the master table to attach the slave table information, which is very convenient and concise. But the corresponding problem is that when I only need to query one of the tables separately, it will query the information of the associated table. Once there is a large amount of associated data, and I do not need the data from the table at this time, the efficiency will be greatly reduced. I would like to ask you gods what good way to associate the query when I need to associate, and not to associate the query when I do not need to associate? Ask for guidance?

public class Class{
        @Id
        private String id;
        @Size(max = 20)
        @Column(unique = true)
        private String code;
        
        @Size(max = 200)
        private String name;
        ...
}

public class Student{
    @Id
    private String id;
    
    @Size(max = 20)
    private String code;
    
    @Size(max = 200)
    private String name;
    
    @ManyToOne
    private Class class;
    ...
}

Baidu said for a moment that adding the annotation @ JsonBackReference, to the setClass of the Student table can prevent the infinite loop containing the other party when the data is converted into json.

@JsonBackReference
public void setClass(Class class) {
        this.class= class;
    }
May.07,2021

has an attribute in @ OneToOne, @ OneToMany, @ ManyToOne that is fetch. You can set two values, one is LAZY, and the other is EAGER.
if it is EAGER, it means that when this piece of data is taken out, its associated data is also taken out and put into memory at the same time.
if it is LAZY, the data associated with it will not be taken out when it is taken out. In the same session, when you want to use it, you can take it (access the database again).
OneToMany defaults to LAZY, and everything else defaults to EAGER.


add fetch = FetchType.LAZY, to @ ManyToOne and load

only when getter is called.
Menu