【问题标题】:Spring Data Jpa Send List As a Search ParameterSpring Data Jpa 发送列表作为搜索参数
【发布时间】:2017-08-23 08:33:46
【问题描述】:
public class Medicine as Entity
       ...
       ...    
    @Lob
    @ManyToMany
    @JoinTable(name = "Medicine_Ingredients")
    private Set<Ingredient> ingredientList = new HashSet<>();

然后我有一个包含成分对象的其他列表。 我想要做的是在存储库中,我想将 List 作为参数推送并获取 Medicines 如果其成分列表包含推送的 List 参数。

我一直在尝试在 for 循环中迭代对象。但我认为这不是一个干净的解决方案。提前致谢!

更新,这段代码暂时阻止了我处理问题的方式,但我认为这不是一个干净的解决方案。走动所有来自这里的药物将是一个问题:

medicineRepository.findByTradeNameStartingWithAndManufacturerStartingWith(
                    medicineSearchModel.getTradeName(),
                    medicineSearchModel.getManufacturer()
            )) 

---- 代码块

        List<Medicine> medicineList = new ArrayList<>();
        ArrayList<String> sub_ingredients = new ArrayList<>();

        for (Ingredient search_ingredient : medicineSearchModel.getIngredientList()) {
            sub_ingredients.add(search_ingredient.getId().toString());
        }
        for (Medicine medicine : medicineRepository.findByTradeNameStartingWithAndManufacturerStartingWith(
                medicineSearchModel.getTradeName(),
                medicineSearchModel.getManufacturer()
        )) {
            ArrayList<String> super_ingredients = new ArrayList<>();
            for (Ingredient medicine_ingredient : medicine.getIngredientList()) {
                super_ingredients.add(medicine_ingredient.getId().toString());
            }
            if (super_ingredients.containsAll(sub_ingredients)) {
                medicineList.add(medicine);
            }
        }
        return medicineList;

【问题讨论】:

  • 向我们展示您的简单工作示例,以便我们弄清楚...
  • @RajaAnbazhagan 我刚刚更新了问题,谢谢!
  • @ManyToMany 不能是@Lob!!! @Lob 是您想要将整个字段序列化为单个列的位置!
  • @BillyFrost 谢谢,尽管您的评论与问题无关。

标签: java spring hibernate spring-data-jpa hql


【解决方案1】:

你可以试试这个。我没有测试这段代码,但我做过类似的事情。

注意:
如果 ing where ing in 不起作用,您可能需要将其更改为 ing where ing.id in 并准备一个成分 ID 列表以设置为参数。

EntityManager em = ...

Query query = em.createQuery("select m from Medicine m left join fetch m.ingredientList ing where ing in :lstIngredient");
query.setParameter("lstIngredient", yourListParam);

【讨论】:

  • EntityManagerFactory 无法解析我们在 persistence.xml 中声明的持久性单元。它是“hibernatepersistenceprovider”
  • 我在您的问题中看到了JPA 标签,我认为您很容易获得 EntityManager 实例。如果你直接使用 Hibernate,你可能会使用 org.hibernate.Session: ``` SessionFactory factory = .. // 我想你有 Session session = factory.getCurrentSession(); Query query = session.createQuery(...同上...); ```
猜你喜欢
  • 2017-06-23
  • 2018-05-20
  • 2018-05-04
  • 2021-02-06
  • 2020-02-03
  • 2020-06-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多