【发布时间】:2022-01-10 04:19:26
【问题描述】:
我正在使用 Spring Data Rest 编辑数据库中的一些实体。
他们都把这个作为基类:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes(
JsonSubTypes.Type(value = TextComponent::class, name = TextComponent.TYPE),
JsonSubTypes.Type(value = TextAreaComponent::class, name = TextAreaComponent.TYPE)
)
abstract class AbstractLabelComponent(
@field:ManyToOne
@field:JsonIgnore
open val template: Template?,
@field:Id
@field:GeneratedValue(strategy = GenerationType.AUTO)
open var id: Long? = null
)
这是一个中产阶级(我不确定它是否重要,所以最好有它):
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
abstract class AbstractTextComponent(
template: Template?,
@field:ManyToOne(optional = false)
open var font: Font,
): AbstractLabelComponent(template)
这是一个子类。只发布一个,因为它们的行为方式都一样。
@Entity
class TextComponent(
template: Template? = null,
font: Font,
): AbstractTextComponent(template){
companion object {
const val TYPE = "text"
}
}
下面是包含组件列表的模板:
@Entity
data class Template(
@field:OneToMany(mappedBy = "template", cascade = [CascadeType.ALL], orphanRemoval = true)
var components: MutableList<AbstractLabelComponent> = mutableListOf()
@field:Id
@field:GeneratedValue(strategy = GenerationType.AUTO)
open var id: Long? = null
)
我正在向 API 发送以下 JSON:
{
"components": [
{
"alignment": 0,
"content": "",
"fieldID": "TEXT",
"font": "/api/fonts/9",
"rotation": 0,
"type": "text",
"x": 84,
"y": 36
}
],
}
但我收到此错误:
JSON 解析错误:[简单类型,类的实例化 com.components.TextComponent] JSON 属性字体的值失败到期 缺少(因此为 NULL)创建者参数字体的值,即 不可为空的类型
我认为这是因为构造函数中的字体属性不是可选的,所以我将其设为可选。但是后来我从数据库收到一个错误,font_id 没有默认值,所以我认为真正的问题是字体没有反序列化或正确传递。
同样奇怪的是,如果我在数组中有字体的 URI,它会抱怨数组无法转换为字体,所以我猜它可以反序列化但它不会将它传递给构造函数。在此之前,我将它作为字体的 JSON,但得到了与现在相同的错误,所以我认为我应该改用 URI。
这是字体类:
@Entity
data class Font(
var humanReadable: String = "",
private val width: Int = 1,
private val height: Int = 1,
@field:Id
@field:GeneratedValue(strategy = GenerationType.AUTO)
open var id: Long? = null
)
我刚刚尝试使用没有 Font 的其他组件,并得到了我提到的相同错误,当我的组件上的字体是可选的时:
java.sql.SQLException: Field 'bold_font_id' doesn't have a default value
这是另一个没有字体的组件:
@Entity
class CodeComponent(
template: Template? = null,
private var code: String = ""
): AbstractLabelComponent(template) {
这是一个具有粗体字体的组件。我在复制以下错误时没有使用它:
@Entity
class TextAreaComponent(
template: Template? = null,
content: String = "",
font: Font,
@field:ManyToOne(optional = false)
var boldFont: Font
): AbstractTextComponent(template, font,content)
这里是模板实体的仓库:
@Repository
interface TemplateRepository: CrudRepository<Template, Long>{
}
【问题讨论】:
-
您能否添加
Template和Font类的代码?谢谢! -
已添加
Font。Template已经存在
标签: json spring kotlin spring-data-rest