mongorepository按typealias查找子类

lp0sw83n  于 2021-07-06  发布在  Java
关注(0)|答案(0)|浏览(174)

我有以下三门课:

@Document(collection = "Product")
public abstract class Product {
    @Id
    private String id;
    // constructor, getters, setters, hash, equals...
}
@TypeAlias("Drink")
@Document(collection = "Product")
public class Food extends Product {
    private String description;
    // constructor, getters, setters, hash, equals...
}
@TypeAlias("Food")
@Document(collection = "Product")
public class Food extends Product {
    private double weight;
    private String description;
    // constructor, getters, setters, hash, equals...
}

为了便于使用,以下存储库:

@Repository
public interface ProductRepository extends MongoRepository<Product, String> {}
@Repository
public interface ProductRepository extends MongoRepository<Product, String> {}
@Repository
public interface ProductRepository extends MongoRepository<Product, String> {}

假设我有以下脚本:

@Autowired
private ProductRepository productRepository;
@Autowired
private FoodRepository foodRepository;
@Autowired
private DrinkRepository drinkRepository;

public void script() {
    Food bread = new Food("Bread", 10.0);
    Drink water = new Drink("Water");
    productRepository.save(bread);
    productRepository.save(water);

    assertEquals(foodRepository.findById(bread.getId()).get(), bread);
    assertEquals(drinkRepository.findById(water.getId()).get(), water);

    // Up to here, I know for a fact it works perfectly

    System.out.println(foodRepository.findAll());

}

问题是最后一次打印会产生以下结果。。。

[
    Food(5fb04c521690dc3f1f7fc1c3)[description='Bread', weight=10.0], 
    Food(5fb04c531690dc3f1f7fc1ce)[description='Water', weight=null]
]

如何获得特定子类(或typealias)的每个产品?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题