【问题标题】:Selecting multiple objects by id using JPA and ObjectDB?使用 JPA 和 ObjectDB 按 id 选择多个对象?
【发布时间】:2014-10-14 16:24:28
【问题描述】:

我无法让 ObjectDB 根据其 ID 选择多个值。我的查询超级简单:

Query query = getEntityManager().createQuery("SELECT i FROM " + getEntityClass().getSimpleName() + " i WHERE i.id IN :ids", entityClass);
query.setParameter("ids", ids);
List<Object> values = query.getResultList();

但无论如何,这总是返回一个空列表。

ids 列表包含现有 id 的列表,所有这些都是 Long 对象。我对此进行了三重检查。

类似的查询:

entityManager.find(getEntityClass(), id);

...和...

Query query = entityManager.createQuery("SELECT i FROM " + getEntityClass().getSimpleName() + " i", entityClass);

...工作正常。

另外,如果我这样做: entityManager.find(getEntityClass(), 1L);

我得到了正确的结果:单个实例。

但是:

List<Long> ids = new LinkedList<Long>();
ids.add(1L);
Query query = getEntityManager().createQuery("SELECT i FROM " + getEntityClass().getSimpleName() + " i WHERE i.id IN :ids", entityClass);
query.setParameter("ids", ids);
List<Object> values = query.getResultList();

values 变量返回一个空列表。

我错过了什么?这是 ObjectDB 不支持的吗?

谢谢!

【问题讨论】:

  • 在 Hibernate/EclipseLink 中确实可以正常工作。我手头没有ObjectDB,也没有兴趣,但您可以尝试使用真正的Set,或者将:ids 包裹在括号内,如IN (:ids)。在大约 5 年前修复错误的旧 Hibernate 版本中也需要这样做。

标签: java jpa jpa-2.0 jpql objectdb


【解决方案1】:

它应该工作。请尝试以下简单测试:

import java.util.*;

import javax.persistence.*;

public class TestInIds {

    public static void main(String[] args) {

        EntityManagerFactory emf =
            Persistence.createEntityManagerFactory(
                "objectdb:$objectdb/db/test.tmp;drop");
        EntityManager em = emf.createEntityManager();

        em.getTransaction().begin();
        em.persist(new MyEntity());
        em.persist(new MyEntity());
        em.getTransaction().commit();

        Query query = em.createQuery("SELECT e FROM MyEntity e WHERE e.id in :ids");
        List<Long> ids = new LinkedList<Long>();
        ids.add(1L);
        query.setParameter("ids", ids);
        List resultList = query.getResultList();
        System.out.println("result size: " + resultList.size());

        em.close();
        emf.close();
    }

    @Entity
    static class MyEntity {
        @Id @GeneratedValue
        private Long id;
    }
}

它应该打印 1。如果它没有尝试最后一个 ObjectDB 版本。 如果您确实得到 1 作为输出,请尝试检查您的应用程序有什么不同。

【讨论】:

  • 感谢您的代码帮助我找到了问题:我的代码传递了一个 ID 列表,但这些项目是 Strings,而不是 Longs。我认为这是正确的,因为我在一个带有签名List&lt;Long&gt; ids 的方法中得到了这个,但显然是一个List&lt;String&gt; 来代替(这是通过注入来的,所以它不会在编译时被捕获)。现在它运行良好,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-26
  • 2013-01-13
  • 2012-02-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多