当集合中有多种类型时,如何让MongoRepository返回正确的类型

时间:2016-01-12 08:30:33

标签: java spring spring-data spring-mongo

使用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类对类型更严格?

依赖关系

  • spring-boot-starter-parent 1.2.7(parent pom)
  • 弹簧引导起动数据的mongodb
  • 弹簧引导起动球衣
  • 弹簧引导起动的Tomcat
  • 弹簧引导起动致动器
  • 弹簧引导起动测试

0 个答案:

没有答案