使用Spring Boot,Spring Data(MongoDB)。假设我有两个具有一些共同超类的类,因此它们位于同一个集合中:
@Document(collection = "automobiles")
public class Automobile {
private String maker;
}
儿童班:
@Document(collection = "automobiles") //not sure if this is needed, but put it in anyway
public class Truck extends Automobile {
}
@Document(collection = "automobiles") //not sure if this is needed, but put it in anyway
public class Van extends Automobile {
}
每种类型的相应MongoRepository:
public interface TruckRepository extends MongoRepository<Truck,String> {
}
public interface VanRepository extends MongoRepository<Van,String> {
}
问题
@Autowired private TruckRepository truckRepository
@Autowired private VanRepository vanRepository
// save 1 of each in a fresh collection
truckRepository.save(new Truck(...));
vanRepository.save(new Van(...));
// try to get all vans
int size = vanRepository.findAll().size() // expect this to be 1, but is 2!
事实上,findAll发现所有的汽车,包括卡车,并下载到范(!!)。如何在不引入类型字段的情况下使Repository类对类型更严格?
依赖关系