简体   繁体   English

如何比较数据库中的整数列表? 爪哇

[英]How to compare Lists of Integers in DB? Java

We have entity:我们有实体:

Class Drink {
Long id;
String name;
List "Integer" ingredients; // We store ingredient's numbers in this list
}

For example: id = 1, name = Mojito, ingredients = {5,7,3,8}例如:id = 1,name = Mojito,成分 = {5,7,3,8}

Let's say, i want to find a drink based on ingredients.比方说,我想根据成分找到一种饮料。 How should I do that?我该怎么做?

  1. Retrieve all cocktails from data base and iterate through them for comparison?从数据库中检索所有鸡尾酒并遍历它们以进行比较?
  2. Or comparison should be conducted in a data-base?还是应该在数据库中进行比较? If this is correct answer, How can I to that?如果这是正确答案,我该怎么做? (How to compare Lists of Integers in the DB)? (如何比较数据库中的整数列表)?

Most likely you'll want to filter the data on the database level.您很可能希望在数据库级别过滤数据。 The exact solution depends on the type of the database structure and the framework that you use, but since you use PostgreSQL, I assume you have a relational database structure, and since you speak of an "entity", I assume you use something like Hibernate or JPA to interact with it.确切的解决方案取决于数据库结构的类型和您使用的框架,但是由于您使用 PostgreSQL,我假设您有一个关系数据库结构,并且由于您说的是“实体”,所以我假设您使用类似 Hibernate 的东西或 JPA 与之交互。

Then probably your drinks should reference their ingredients not as numbers, but as entities.那么您的饮料可能不应该将其成分作为数字,而是作为实体来引用。 This is how the mapping could look like:这就是映射的样子:

class Drink {

    Long id;

    String name;

    @ManyToMany
    @JoinTable(tableName = "drink_ingredients")
    List<Ingredient> ingredients;
}

class Ingredient {

    Long id;

    String name;
}

Then a query to find all drinks containing a specific ingredient would be:然后查找所有包含特定成分的饮料的查询将是:

Query query = entityManager.createQuery("select d from Drink d " 
    + "join d.ingredients i "
    + "where i.name = :ingredientName");
query.setParameter("ingredientName", "Lime");
List<Drink> drinks = (List<Drink>) query.getResultList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM