加入了继承策略
一个 Sample 类图,我们将在其上看到 JPA 实现。
@Entity
@Table(name = "VEHICLE")
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "VEHICLE_TYPE")
public abstract class Vehicle {
@TableGenerator(name = "VEHICLE_GEN", table = "ID_GEN", pkColumnName = "GEN_NAME", valueColumnName = "GEN_VAL", allocationSize = 1)
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "VEHICLE_GEN")
private int idVehicle;
private String manufacturer;
// getters and setters
}
TransportationVehicle.java
@MappedSuperclass
public abstract class TransportationVehicle extends Vehicle {
private int loadCapacity;
// getters and setters
}
Truck.java
@Entity
public class Truck extends TransportationVehicle {
private int noOfContainers;
// getters and setters
}
PassengerVehicle.java
@MappedSuperclass
public abstract class PassengerVehicle extends Vehicle {
private int noOfpassengers;
// getters and setters
}
Car.java
@Entity
public class Car extends PassengerVehicle {
private int noOfDoors;
// getters and setters
}
Bike.java
@Entity
public class Bike extends PassengerVehicle {
private int saddleHeight;
// getters and setters
}
测试代码
/* Create EntityManagerFactory */
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("AdvancedMapping");
/* Create EntityManager */
EntityManager em = emf.createEntityManager();
EntityTransaction transaction = em.getTransaction();
transaction.begin();
Bike cbr1000rr = new Bike();
cbr1000rr.setManufacturer("honda");
cbr1000rr.setNoOfpassengers(1);
cbr1000rr.setSaddleHeight(30);
em.persist(cbr1000rr);
Car aventador = new Car();
aventador.setManufacturer("lamborghini");
aventador.setNoOfDoors(2);
aventador.setNoOfpassengers(2);
em.persist(aventador);
Truck truck = new Truck();
truck.setLoadCapacity(1000);
truck.setManufacturer("volvo");
truck.setNoOfContainers(2);
em.persist(truck);
transaction.commit();
数据库图如下。
连接继承策略的优点是它不会像单表策略那样浪费数据库空间。另一方面,由于每次插入和检索都涉及多个连接,因此当继承层次结构变宽和变深时,性能就成了问题。
可以在此处阅读完整的解释示例