Spring Boot JPA,如果我有多个具有相同列名的表,我可以放入同一个实体类吗?

Mic*_*tta 3 multiple-columns spring-data-jpa spring-boot

我在自定义 SQL 语句中使用 as 子句,在实体类中我使用 as 子句中的名称。拥有多个具有相同列名的表的最佳方法是什么?单独的实体类?

Gus*_*ini 7

您可以有一个抽象类,您将在其中定义所有用列名称注释的公共字段,并用MappedSuperclass对其进行注释。

然后,对于共享相同列名称的每个不同表,您创建一个扩展抽象类的新类,并使用表名称对其进行注释。

这样您就不必重复它们共有的列的定义。

@MappedSuperclass
abstract class Person {
    // Common columns

    @Id
    @Column(name = "ID")
    private Long id;

    @Column(name = "AGE")
    private Integer age;

    // getters, setters, hashCode, equals...
}

@Entity
class Employee extends Person {
    // This entity will include 'ID' and 'AGE' columns from 'Person'

    @Column(name = "SALARY")
    private BigDecimal salary;

    // getters, setters, hashCode, equals...
}

@Entity
class Student extends Person {
    // This entity will include 'ID' and 'AGE' columns from 'Person'

    @Column(name = "FIELD")
    private String field;

    // getters, setters, hashCode, equals...
}
Run Code Online (Sandbox Code Playgroud)