加入了繼承策略

一個 Sample 類圖,我們將在其上看到 JPA 實現。 StackOverflow 文件

@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();

資料庫圖如下。 StackOverflow 文件

連線繼承策略的優點是它不會像單表策略那樣浪費資料庫空間。另一方面,由於每次插入和檢索都涉及多個連線,因此當繼承層次結構變寬和變深時,效能就成了問題。

可以在此處閱讀完整的解釋示例