在使用jpa时,使用关联关系时,发现懒加载时会和json序列化冲突,导致懒加载失败。
创建三个表:
school 、teacher 、student
school和teacher是一对多的关系,teacher和student是多对一的关系。
sql
CREATE TABLE school(
id INT AUTO_INCREMENT PRIMARY KEY,
school_name VARCHAR(100) COMMENT '学校名称'
)
INSERT INTO school(school_name)VALUES("xx学校");
CREATE TABLE teacher(
id INT AUTO_INCREMENT PRIMARY KEY,
teacher_name VARCHAR(100) COMMENT '老师名称',
school_id INT COMMENT '学校id'
)
INSERT INTO teacher(teacher_name,school_id)VALUES("老师1",1);
INSERT INTO teacher(teacher_name,school_id)VALUES("老师2",1);
INSERT INTO teacher(teacher_name,school_id)VALUES("老师3",1);
CREATE TABLE student(
id INT AUTO_INCREMENT PRIMARY KEY,
student_name VARCHAR(100) COMMENT '学生名称',
teacher_id INT COMMENT '老师id'
)
INSERT INTO student(student_name,teacher_id)VALUES("学生1",1);
INSERT INTO student(student_name,teacher_id)VALUES("学生2",1);
INSERT INTO student(student_name,teacher_id)VALUES("学生3",1);
INSERT INTO student(student_name,teacher_id)VALUES("学生4",2);
INSERT INTO student(student_name,teacher_id)VALUES("学生5",2);
INSERT INTO student(student_name,teacher_id)VALUES("学生6",2);
INSERT INTO student(student_name,teacher_id)VALUES("学生7",3);
INSERT INTO student(student_name,teacher_id)VALUES("学生8",3);
INSERT INTO student(student_name,teacher_id)VALUES("学生9",3);
controller类
@RestController
public class SchoolController {
@Autowired
private SchoolRepo schoolRepo;
@GetMapping("/list")
public List<School> querySchool() {
return schoolRepo.findAll();
}
}
坑1:首先先遇到的是转json时互相引用,陷入死循环的问题!
解决方案如下:
使用@JsonIgnoreProperties,json序列化时忽略某些属性
修改代码:
school类
@OneToMany(fetch=FetchType.LAZY,mappedBy="school")
@JsonIgnoreProperties("school")
private List<Teacher> teacherList;
teacher类
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="school_id",referencedColumnName="id")
@JsonIgnoreProperties("teacherList")
private School school;
@OneToMany(fetch=FetchType.LAZY,mappedBy="teacher")
@JsonIgnoreProperties("teacher")
private List<Student> studentList;
student类
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="teacher_id",referencedColumnName="id")
@JsonIgnoreProperties("studentList")
@NotFound(action= NotFoundAction.IGNORE)
private Teacher teacher;
坑2:No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer
在实体类中 发现有字段为null,在转化成json的时候,fasterxml.jackson将对象转换为json报错
解决方案如下:
使用@NotFound(action= NotFoundAction.IGNORE) 注解,找不到引用的外键数据时忽略,NotFound默认是exception
修改代码:
teacher类
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="school_id",referencedColumnName="id")
@JsonIgnoreProperties("teacherList")
@NotFound(action= NotFoundAction.IGNORE)
private School school;
student类
@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="teacher_id",referencedColumnName="id")
@JsonIgnoreProperties("studentList")
@NotFound(action= NotFoundAction.IGNORE)
private Teacher teacher;
坑3:运行发现懒加载并没有起作用!
解决方案如下:
映入pom文件
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate5</artifactId>
<version>2.9.8</version>
</dependency>
yml文件开启懒加载
jpa:
open-in-view: true
properties:
hibernate:
enable_lazy_load_no_trans: true
config文件
package com.ganlong.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.hibernate5.Hibernate5Module;
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
/**
* 解决jpa懒加载
*/
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper mapper = converter.getObjectMapper();
mapper.registerModule(hibernate5Module());
return converter;
}
@Bean
public Hibernate5Module hibernate5Module() {
Hibernate5Module module = new Hibernate5Module();
module.disable(Hibernate5Module.Feature.USE_TRANSIENT_ANNOTATION);
module.enable(Hibernate5Module.Feature.SERIALIZE_IDENTIFIER_FOR_LAZY_NOT_LOADED_OBJECTS);
return module;
}
}
坑4:@ManyToOne(fetch=FetchType.LAZY)这样设置懒加载失效,要将optional=false。
@ManyToOne(fetch=FetchType.LAZY)和@NotFound(action= NotFoundAction.IGNORE)冲突,设置了@NotFound后@ManyToOne的懒加载就会失效!这个没找到解决方案。
坑5:hibernate会自动关闭session,这样,当要使用子数据的时候,系统会抛出lazyinit的错误。
解决方案如下:
yml文件:
open-in-view: true
config文件:
@Bean
public OpenEntityManagerInViewFilter openEntityManagerInViewFilter() {
OpenEntityManagerInViewFilter openEntityManagerInViewFilter= new OpenEntityManagerInViewFilter();
openEntityManagerInViewFilter.setEntityManagerFactoryBeanName("chexAdminJpaEntityManagerFactory");
return openEntityManagerInViewFilter;
}
坑6:加载多条sql的问题!未解决