我下面有一个这样的模型:
@Entity(name = "request")
public class VisitRequest {
@Id
@GeneratedValue
private Long id;
@OneToMany(mappedBy = "visitRequest", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonManagedReference
private List<Visitor> visitors;
//default constructor, getters and setters
}
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class")
public class Visitor {
@Id
@GeneratedValue
private Long id;
@ManyToOne
@JsonBackReference
private VisitRequest visitRequest;
//default constructor, getters and setters
}
@Entity
public class ContactPerson extends Visitor {
private PhoneNumber phoneNumber;
//default constructor, getters and setters
}
但是,当我尝试通过与一位访客交换一位访客来更新visitRequest,并尝试在CRUD存储库中执行该方法visitRequestRepository.save(visitRequest);时,我收到此异常:
也许问题在于数据库中的contact_person和visitor表中使用了相同的ID?
我该如何解决这个问题?我一直在寻找解决方案,但没有一个对我有用。
最佳答案
您可能没有在visitRequest
中初始化ContactPerson
引用。请看一下以下配置,它与Spring Boot JPA一起使用。我已经使用lombok生成Getter
和Setters
。
这是在Spring Boot https://github.com/ConsciousObserver/SpringBootJpaInheritance中实现的工作示例
@Data
@Entity(name = "request")
class VisitRequest {
@Id
@GeneratedValue
private Long id;
@OneToMany(mappedBy = "visitRequest", cascade = CascadeType.ALL, orphanRemoval = true)
@JsonManagedReference
private List<Visitor> visitors = new ArrayList<>();
}
@NoArgsConstructor
@Data
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class")
class Visitor {
@Id
@GeneratedValue
private Long id;
@ManyToOne
@JsonBackReference
private VisitRequest visitRequest;
public Visitor(VisitRequest visitRequest) {
this.visitRequest = visitRequest;
}
}
@NoArgsConstructor
@Data
@ToString(callSuper = true)
@EqualsAndHashCode(callSuper = true)
@Entity
class ContactPerson extends Visitor {
private String phoneNumber;
public ContactPerson(VisitRequest visitRequest, String phoneNumber) {
super(visitRequest);
this.phoneNumber = phoneNumber;
}
}