使用 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 找到了包括卡车在内的所有汽车,并向下转换为 Van (!!)。如何在不引入类型字段的情况下使 Repository 类对类型更加严格?
依赖项
- spring-boot-starter-parent 1.2.7(父 pom)
- spring-boot-starter-data-mongodb
- 弹簧靴启动球衣
- spring-boot-starter-tomcat
- 弹簧引导启动器执行器
- 弹簧引导启动器测试