[英]How to prevent a subclass from inheriting a field from the superclass using Hibernate?
I have a class A which has a List of a class B. Since the attributes of a A is similar to what a B has, I thought about using inheritance to solve my problem.我有一个 class A,它有一个 class B 的列表。由于 A 的属性与 B 的属性相似,我考虑使用 inheritance 来解决我的问题。 But I don't want B to have a list to B, and here is my problem.但我不希望 B 有 B 的列表,这是我的问题。 How can I prevent B from inheriting the List of B from the super-class?如何防止 B 从超类继承 B 的列表?
The super-class:超类:
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Data
@SuperBuilder
@Inheritance(strategy = InheritanceType.JOINED)
public class A
{
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
protected Integer id;
@OneToMany(mappedBy = "a")
private List<B> list = new ArrayList<>();
// other fields that I want to be inherited...
}
The subclass:子类:
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
@SuperBuilder
public class B extends A
{
@JsonIgnore
@ManyToOne
@JoinColumn
private A a;
}
The JSON returned after creating the class A:创建class后返回JSON A:
{
"id": 1,
// other fields
"list": [
{
"id": 2,
// inherited fields
"list": [], // I want to prevent this!
}
],
}
And one last thing, the reason why I want to use inheritance in this case instead of creating a B class with its own fields it's because I am using a composite key for solving another problem, and both classes share this composite key.最后一件事,为什么我想在这种情况下使用 inheritance 而不是创建具有自己字段的 B class 的原因是因为我正在使用复合键来解决另一个问题,并且两个类共享这个复合键。
You can either create a dto for class B to specify what you want to show or you can @jsonignore List in class A if you don't need to send A as a JSON您可以为 class B 创建一个 dto 以指定要显示的内容,或者如果您不需要将 A 作为 JSON 发送,则可以在 class A 中@jsonignore List
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.