【发布时间】:2017-09-01 23:07:28
【问题描述】:
我想我想在这里吃我的蛋糕,但我们会看看是否有一个可行的解决方案来解决我正在寻找的问题。我有一个 Spring Boot/JPA/Hibernate 应用程序,它将与 MySQL 作为其后备存储进行通信。我有几种情况,从 OOP 的角度来看,我的实体类形成了这样的父/子层次结构:
// Groovy pseudo-code!
class Vehicle {
Long id
Long maxSpeed
String make
String model
}
class Motorcycle extends Vehicle {
Boolean isTwoStroke
}
class Car extends Vehicle {
Boolean hasLeatherInterior
}
等等。通常,在 JPA 之外,我可能会像这样设计它们各自的表:
CREATE TABLE motorcycles (
motorcycle_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
motorcycle_max_speed BIGINT UNSIGNED,
motorcycle_make VARCHAR(50) NOT NULL,
motorcycle_model VARCHAR(50) NOT NULL,
motorcycle_is_two_speed BIT NOT NULL,
# PK, FK, UC, index constraints down here (omitted for brevity)
);
CREATE TABLE cars (
car_id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
car_max_speed BIGINT UNSIGNED,
car_make VARCHAR(50) NOT NULL,
car_model VARCHAR(50) NOT NULL,
car_has_leather_interior BIT NOT NULL,
# PK, FK, UC, index constraints down here (omitted for brevity)
);
理想情况下我想保持这个表格设计原样,“父车辆”列的名称与我上面的一样。但是,如果我正确理解了 Hibernate/JPA API,那么我不认为在不做出某种牺牲的情况下是不可能的。我认为我要么需要牺牲应用层的继承,以便我可以完全按照我在数据库中的名称命名子类中的列:
@Entity
class Motorcycle { // No longer extends Vehicle :-(
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "motorcycle_id")
Long id
@Column(name = "motorcycle_max_speed")
Long maxSpeed
@Column(name = "motorcycle_make")
String make
@Column(name = "motorcycle_model")
String model
@Column(name = "motorcycle_is_two_speed")
Boolean isTwoStroke
}
@Entity
class Car { // No longer extends Vehicle :-(
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "car_id")
Long id
@Column(name = "car_max_speed")
Long maxSpeed
@Column(name = "car_make")
String make
@Column(name = "car_model")
String model
@Column(name = "car_has_leather_interior")
Boolean hasLeatherInterior
}
或者我认为我可以保留应用层继承,但随后需要像这样重构我的数据库表:
CREATE TABLE motorcycles (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
max_speed BIGINT UNSIGNED,
make VARCHAR(50) NOT NULL,
model VARCHAR(50) NOT NULL,
motorcycle_is_two_speed BIT NOT NULL,
# PK, FK, UC, index constraints down here (omitted for brevity)
);
CREATE TABLE cars (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
max_speed BIGINT UNSIGNED,
make VARCHAR(50) NOT NULL,
model VARCHAR(50) NOT NULL,
car_has_leather_interior BIT NOT NULL,
# PK, FK, UC, index constraints down here (omitted for brevity)
);
所以我问:我是否可以保留我的应用层继承(并让 Motorcycle 和 Car 从 Vehicle 继承这些属性)并保留我的数据库表列使用我的首选约定命名?
【问题讨论】:
标签: java hibernate jpa inheritance groovy