1

Spring Boot、Spring Data (MongoDB) を使用します。いくつかの共通のスーパー クラスを持つ 2 つのクラスがあるとします。したがって、これらは同じコレクションに含まれます。

@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 はトラックを含むすべての自動車を検出し、バン (!!) にダウンキャストしました。タイプフィールドを導入せずに、リポジトリクラスをタイプに関してより厳密にする方法は?

依存関係

  • spring-boot-starter-parent 1.2.7 (親 pom)
  • spring-boot-starter-data-mongodb
  • 春ブーツスタータージャージ
  • spring-boot-starter-tomcat
  • スプリングブートスターターアクチュエーター
  • スプリングブートスターターテスト
4

0 に答える 0