我设计的数据库使用 Table Per Class 的继承策略,其中公共字段存在于派生表中以及父表中。一些简单的模型看起来像这样。
Vehicle.java
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Vehicle {
@Id @GeneratedValue
private int id;
private String name;
private String brand;
}
Car.java
@Entity
public class Car extends Vehicle {
private String oil;
}
Bike.java
@Entity
public class Bike extends Vehicle {
private String frame;
}
现在,我想对所有类型的VehicleRepository
个对象进行统一Vehicle
,包括Car
和Bike
。
存储库可能看起来像这样。
VehicleRepository.java
@Repository
public interface VehicleRepository extends CrudRepository<Vehicle, Integer> {
@Query("SELECT v FROM Vehicle e WHERE v.vehicleId = ?1")
public Vehicle findById(Integer vehicleId);
}
所以我希望能够做类似的事情。
int carId = 3; // I know that in the DB there's a car with that ID
int bikeId = 7; // I know that in the DB there's a bike with that ID
// the important part
Car car = (Car) repo.findById(carId);
Bike bike = (Bike) repo.findById(bikeId);
// now I want to be able to call:
car.getOil();
bike.getFrame();
问题是:这是否有效,这是一个很好的模式吗?
答案 0 :(得分:0)
您可以在Vehicle
中添加所有字段,并尝试使用Car
Bike
和@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Vehicle {
@Id @GeneratedValue
private int id;
private String name;
private String brand;
private String oil;
private String frame;
}
。
Car
对于Bike
和public interface VehicleProjection {
public int getId();
public String getBrand();
public String getName();
}
public interface Car extends VehicleProjection {
public String getOil();
}
public interface Bike extends VehicleProjection {
public String getFrame();
}
,您可以使用投影:
public interface CarRepository extends Repository<Vehicle, Integer> {
public Car findById(Integer carId);
}
您的存储库应如下所示:
Bike
import os
import glob
import csv
def check(filename):
if 'DELIVERY NOTIFICATION' in open(filename).read():
isDenied = True
print ("This claim was Denied")
print (isDenied)
elif 'Dear Customer:' in open(filename).read():
isDenied = False
print("This claim was Approved")
print (isDenied)
else:
print("I don't know if this is approved or denied")
def iterate():
path = 'text/'
for infile in glob.glob(os.path.join(path, '*.txt')):
print ('current file is:' + infile)
filename = infile
check(filename)
iterate()
存储库