将 Parent 发送到方法,然后在数据库中查找 AllBy
我的数据库有 3 个表。产品,加入佐餐啤酒和加入薯条
class Product {
String name;
String type;
int actualAmount;
int goalAmount;
}
class Beer extends Product {
int liters;
int percentage;
}
class Chips extends Product {
int weight;
String taste;
}
class ProductService {
private final ProductRepository repo;
//Send parent to method then getAll similar products by child variables.
public void foo(Product product) {
if (product instanceof Beer) {
Beer beer = (Beer) product;
List<Beer> fromDb = repo.findAllByPercentage(beer.getPercentage());
}
else if (product instanceof Chips) {
Chips chips = (Chips) product;
List<Chips> fromDb = repo.findAllByTaste(chips.getTaste());
}
}
}
从 Java 17 开始(我认为)你可以这样做:
if (product instanceof Beer beer) {
List<Beer> fromDb = repo.findAllByPercentage(beer.getPercentage());
} else if (product instanceof Chips chips) {
List<Chips> fromDb = repo.findAllByTaste(chips.getTaste());
}