有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在没有警告的情况下从hibernate获取结果元素

在hibernate中,我总是进行查询,并从中获取记录,如下所示:

Query q = em.createQuery("FROM Product WHERE productCode=:productCode");
    q.setParameter("productCode", productCode);
    if(q.getResultList().isEmpty()) {
        return null;
    }       
    Iterator i = q.getResultList().iterator();
    Product pp = null;
    if(i.hasNext()) {
        pp = (Product)i.next();
    }

但每次我使用迭代器时,我都会得到这个警告

Iterator is a raw type. References to generic type Iterator should be parameterized

所以我试着用 Iterator< Product> getElement = q.getResultList().iterator();但在此之后,我有一个新的警告:

Type safety: The expression of type Iterator needs unchecked conversion to conform to Iterator

但在那之后,我用"(Iterator< Product >)q.getResultList().iterator();"改变了主意,出现了一个新的警告:

Type safety: Unchecked cast from Iterator to Iterator

所以我认为我做错了什么,但是什么呢?有什么建议吗


共 (1) 个答案

  1. # 1 楼答案

    试用:

    TypedQuery<Product> q = em.createQuery("FROM Product WHERE productCode=:productCode", Product.class);
    q.setParameter("productCode", productCode);
    if(q.getResultList().isEmpty()) {
        return null;
    }       
    List<Product> results = q.getResultList();
    Iterator<Product> i = results.iterator();
    Product pp = null;
    if(i.hasNext()) {
        pp = i.next();
    }
    

    编辑:我使用了这个源代码http://www.objectdb.com/java/jpa/query/execute 非常重要:

    Both Query and TypedQuery define a getResultList method, but the version of Query returns a result list of a raw type (non generic) instead of a parameterized (generic) type