[英]Spring Boot: Prevent persisting field declared in superclass
I am creating a Todo app in Spring Boot and I need to create two tables: Task
and Todo
( Todo
extends Task
).我正在 Spring Boot 中创建一个 Todo 应用程序,我需要创建两个表:
Task
和Todo
( Todo
extends Task
)。
In Task
table is a field called description
and I would like to prevent that column to be created in Todo
table.在
Task
表中有一个名为description
的字段,我想防止在Todo
表中创建该列。
How can I do it?我该怎么做?
Task(parent):任务(父):
package com.example.todo.model;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Task {
@Id
private long id;
private String name;
private String description;
}
Todo(child):待办事项(儿童):
package com.example.todo.model;
import javax.persistence.Entity;
import javax.persistence.Transient;
@Entity
public class Todo extends Task {
private boolean isChecked;
}
I would suggest you clean up your design because concrete classes inheriting from other concrete classes is (often) a code smell.我建议您清理您的设计,因为从其他具体类继承的具体类(通常)是一种代码味道。 The proper solution to this is to factor out the common parts of both classes into a (abstract) super class and then add the specific fields to the concrete inheriting classes:
正确的解决方案是将两个类的公共部分分解成一个(抽象的)super class,然后将特定字段添加到具体的继承类中:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Completable {
@Id
private long id;
private String name;
}
@Entity
public class Task extends Completable {
private String description;
}
@Entity
public class Todo extends Completable {
private boolean isChecked;
}
so you have the behaviour grouped in the classes where it belongs and don't have to make sure that one thing contains a description while it shouldn't.因此您可以将行为分组到它所属的类中,并且不必确保某件事包含描述,而它不应该包含描述。
What you want cannot be done easily.你想要的东西不容易做到。 But you might be trying to solve an issue in the wrong way.
但是您可能试图以错误的方式解决问题。
From what I am reading you have a Task
entity with has two separate types:根据我正在阅读的内容,您有一个具有两种不同类型的
Task
实体:
If this is the case you might want to model the classes the same way.如果是这种情况,您可能希望 model 以相同的方式上课。 Thus having:
因此有:
Task
entity without the descriptionTask
实体Todo
entity extending Task
with the checkboxTask
的Todo
实体SummaryTask
extending Task
with a description fieldSummaryTask
扩展Task
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.