gpt4 book ai didi

java - 如何使用 DiscriminatorValue 保存实体

转载 作者:行者123 更新时间:2023-12-01 10:03:17 25 4
gpt4 key购买 nike

我有两个实体 UserCandidat ,其中 Candidat 扩展了类 User ,如下所示:

用户实体:

@Entity
@Table(name="users")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="TYPE_USER",discriminatorType=DiscriminatorType.STRING,length=2)

@JsonTypeInfo(use=JsonTypeInfo.Id.NAME,include=JsonTypeInfo.As.PROPERTY,property="type")
@JsonSubTypes({
@Type(name="UC",value=Candidat.class)
})

@XmlSeeAlso({Candidat.class})
public class User implements Serializable {
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Long codeUser;
//other code ...

候选实体:

@Entity
@DiscriminatorValue("UC")
@XmlType(name = "UC")
public class Candidat extends User {
private String codeMassar;

为了保存新的候选人,我调用这个存储库方法:

candidatRepository.save()

来自:

public interface CandidatRepository extends JpaRepository<Candidat, String> {

}

这是我调用 save 方法的休息服务:

@RequestMapping(value = "/candidats", method = RequestMethod.POST)
public Candidat saveCandidat(@RequestBody Candidat candidat) throws Exception {
return candidatMetier.saveCandidat(candidat);
}

问题是当我想保存一个新的候选人时,如下所示:

{
"username": "User",
"password": "123456",
"email": "user@gmail.com"
}

我收到一条错误消息:

Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: Could not read document: Unexpected token (END_OBJECT), expected FIELD_NAME: missing property 'type' that is to contain type id (for class org.capvalue.fme.domain.Candidat)

据我了解,我必须在要发送的 JSON 对象中指定类型,但我认为这没有必要,因为我保存了一个新的 Candidat ,其中包含 @DiscriminatorValue("UC") ,所以当它的 saveUser 中时表它将自动与 type='UC' 一起保存。

我该如何解决这个问题?

最佳答案

what I understand from it that I have to specify the type in the json object I'm sending

由于您已添加 @JsonTypeInfo,因此您应该使用 type 字段指定对象实例的实际类。例如,如果您将 type 字段设置为 UC,Jackson 将创建 Candidat 类的实例。

but I dont think that's necessary because I save a new Candidat which has the @DiscriminatorValue("UC") so when its save in the User table it will be saved with type='UC' automatically.

@DiscriminatorValue 将由您的 JPA 提供程序处理。相反,@JsonTypeInfo 是 Jackson 的概念,所以不!您不能指望 JPA @DiscriminatorValue 帮助 Jackson 确定对象实例的实际类型。

您应该以 JSON 表示形式发送 type 信息,或者从您的 User 中删除 @JsonTypeInfo@JsonSubTypes > 类。我想删除 Jackson 类型注释是更好的方法,因为您在以下位置使用实际的子类:

public Candidat saveCandidat(@RequestBody Candidat candidat) { ... }

此外,尝试定义一些DTO并将它们作为 REST 端点返回值返回。这种方法的一个优点是您的 Jackson 和 JPA 元数据是分开的,因此您可以避免这些问题。

关于java - 如何使用 DiscriminatorValue 保存实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36649683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com