java - 无法使用地图保存 Objectify 实体在嵌入式课程中?
问题描述
我有一个嵌入式实体,它的字段类型为 Map<String, Object>。
Map 的所有键都是 String 类型。
下面是实体
@Entity
@Index
@Getter @Setter
public class NiftySurveys {
@Id
private Long id;
private List<SurveyQuestions> questions;
private Long createddate;
private Long updatedDate;
}
@Getter @Setter
public class SurveyQuestions {
private String label;
private String code;
private SurveyQuestionGroups questionGroup;
private Map<String,Object> optionGroup;
}
我无法使用 optionGroup 保存实体。
从前端提交的示例实体
{
"questions": [{
"label": "jio",
"code": null,
"questionGroup": {
"name": "Date Time",
"value": "DATI"
},
"optionGroup": {
"labels": [{
"label": "Date / Time"
}],
"collectDateInfo": true,
"collectTimeInfo": true,
"dateFormat": "MM/DD/YYYY",
"validationMessage": "Please Enter a Valid Date!"
}
}, {
"code": null,
"label": "Q2",
"questionGroup": {
"name": "Multiple Choice Questions",
"value": "MCQ"
},
"optionGroup": {
"name": "Agree - Disagree",
"code": "AGDAG",
"options": [{
"label": "YES",
"value": "Y"
}, {
"label": "NO",
"value": "N"
}]
}
}]
}
地图的所有键都是字符串。
错误信息:
exception: "com.googlecode.objectify.SaveException"
message: "Error saving com.nifty.niftyfeedbacks.domain.NiftySurveys@4ac88d5e: java.lang.IllegalStateException: Embedded Map keys must be of type String/Enum/Key<?> or field must specify @Stringify"
链接到堆栈跟踪 https://drive.google.com/file/d/1fqpPLiJutWLif5GnrlqLEZ6Wr_PdLdC-/view?usp=sharing
解决方案
要了解 @Stringify 的工作原理,请查看https://github.com/objectify/objectify/wiki/Entities#stringify:
In order to use non-String keys with Maps, you may specify the @Stringify annotation:
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Stringify;
import com.googlecode.objectify.stringifier.Stringifier;
class DateStringifier implements Stringifier<LocalDate> {
@Override
public String toString(LocalDate obj) {
return obj.getString();
}
@Override
public LocalDate fromString(String str) {
return new LocalDate(str);
}
}
@Entity
class Car {
@Id Long id;
@Stringify(DateStringifier.class)
Map<LocalDate, ServiceRecord> serviceHistory = new HashMap<>();
}
先前的响应:错误消息很清楚:您必须提供“字符串方式”来处理您的嵌入式实体。toString()
因此,您应该在嵌入式实体中编写一个方法或@Stringify
根据需要使用注释。
它似乎是 JSON,所以您是否尝试使用 @JsonUnwrapped :@see https://stackoverflow.com/a/10077262/390462
class Item {
private String title;
@JsonProperty("date")
private Date createdAt;
// How to map this?
@JsonUnwrapped
private Author author;
}
您也可以通过一个很好的 JPA 教程来处理嵌入式对象:
推荐阅读
- docker - 如何在特定时间停止 docker 容器?(24小时重置)
- sql - 如何用 SQL 中前几天的最新值替换缺失的行?
- sql-server - SQuirrel_SQL_Client_3.7.1 无法连接到 SQL Server 2016 SSL 错误
- powerbi - PowerBI DAX:创建接受来自同一表的部分视觉过滤器的度量
- c# - 试图将 Json 反序列化为对象
- python - flask.request mocker.patch.object 不生效
- sap - 哈希分区在hana中有4列
- angular8 - angular-8 中的 ngModel。如何存储用户接受的数据?
- java - 如何在正文中添加“受众”以获取 OAuth2 令牌?
- c# - 绑定到 dbcontext/dataset 的主从数据网格未过滤