假设我有一个看起来像这样的实体:
@Entity
public class Garage {
...
@Column(unique = true, nullable = false)
private String garageId;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, mappedBy = "garage")
private Set<Vehicle> vehicles = new HashSet<>();
...
}
车辆实体如下所示:
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Vehicle{
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "garage_id", referencedColumnName = "garageId", nullable = false)
private Garage garage;
我有两个从车辆继承的子实体,它们可能看起来像跟随
@Entity
public class Truck extends Vehicle {
...
}
@Entity
public class Motorcycle extends Vehicle {
...
}
在Spring Data JPA中,我如何查询包含摩托车的车库?抛出另一个问题,有没有办法强制Garage可能只有每个子实体中的一个? (车库可能包含1辆卡车+ 1辆摩托车但不超过1辆特定车辆)
答案 0 :(得分:0)
我假设你有一个Garage的存储库,在该接口中定义了以下方法。
List<Garage> findByVehicles(Vehicle vehicle);
然后,假设你有一个叫Motor的Motorcyle实例,你可以用
来调用它List<Garage> garagesWithMotorcyle = garageRepository.findByVehicles(motorcyle);