Mybatis lazy loading and @ResponseBody annotation conflict

Mybatis lazy loading and @ResponseBody annotation conflict

When there are multiple tables in the project, Mybatis lazy loading may be used. If it is an SSM project, when the foreground requests data, the background returns data. If the Controller uses the @ResponseBody annotation, Mybatis' lazy loading will be invalid (printing the log). Sometimes you will find that the sql statement that queries the sub-table data will still be sent).

The principle of this problem is that when the method annotated with @ResponseBody is used to return data, jackson will be used to call the get method of the class during the serialization process, and the lazy loading of Mybatis is triggered when the get method is called. It doesn't make sense.

There are a variety of solutions according to the requirements. Add the @JsonIgnore annotation to the method or property, and the property will be ignored during serialization so that it does not participate in json conversion, but there will be a problem. If this property is required for this approach At once…

Another way is to use the @JsonIgnore and @JsonGetter annotations together.

For example, Department (Dept) and Teacher (Teacher), add @JsonIgnore to the get method of the teacher class attribute of the department class, write another method, the method body is the same as the get method, the method name does not matter, and then add @JsonGetter to this method .

@JsonIgnore
public List<Teacher> getTeachers() {//默认的get方法
    return teachers;
}

@JsonGetter(value = "teachers")
public List<Teacher> getDetail() {//自定的方法
    return teachers;
}

public void setTeachers(List<Teacher> teachers) {
    this.teachers = teachers;
}

This will allow jackson to call the custom getDetail method without using the get method during serialization, and avoid calling the get method to trigger the lazy loading of mybatis.

And what is the meaning of lazy loading. When multiple tables are associated, if lazy loading is not enabled, there will be a stack over flow problem. It is still the department and teacher. When I go to query the department table, I will check the teacher table and assign the value of the list teachers of the department. At this time, I will check the subordinate teachers of the department. When I find the teacher, the teacher also has the Dept dept attribute. Go check the department to which the teacher belongs, and there is no result in this reciprocating cycle, which eventually leads to a stack explosion. Lazy loading is to check when you use it, and you don't check it when you don't need it, which will avoid unnecessary queries and improve efficiency.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324706517&siteId=291194637