springboot实体化类的集合属性序列化

springboot2.1.6项目问题记录

entity下的实体类文件QuestionManage,java
原来有如下字段:

@Column(columnDefinition="varchar(20) COMMENT '问题对应的父任务ID'")
private  String parentQuestionId;

Column(columnDefinition = "varchar(255) COMMENT '子任务ID列表'")
@ElementCollection
private List<String> childQuestionIds = new ArrayList<>();



public String getParentQuestionId() {
		return parentQuestionId;
	}

	public void setParentQuestionId(String parentQuestionId) {
		this.parentQuestionId = parentQuestionId;
	}

public List<String> getChildQuestionIds() {
		return childQuestionIds;
	}

public void setChildQuestionIds(List<String> childQuestionIds) {
		this.childQuestionIds = childQuestionIds;
	}

启动后,调用此表search接口获取数据列表报错:

nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.java456.entity.QuestionManage.childQuestionIds

分析:
初始化序列化失败
方法:
禁用懒加载:在实体类中将集合属性改为立即加载(EAGER),这样在序列化时就能获取集合的数据。或者DTO,此处直接懒加载。

在childQuestionIds字段修改后:


Column(columnDefinition = "varchar(255) COMMENT '子任务ID列表'")
@ElementCollection(fetch = FetchType.EAGER)  //在实体类中将集合属性改为立即加载(EAGER),这样在序列化时就能获取集合的数据(否则报错nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.java456.entity.QuestionManage.childQuestionIds)
private List<String> childQuestionIds = new ArrayList<>();

你可能感兴趣的:(spring,boot,后端,java)