繁体   English   中英

在JPA中修改查询结果

[英]Modifying Query Result in JPA

EntityManager em = EMF.get().createEntityManager();
EntityTransaction tx = null;

List<Profile> list = null;
Query q = null;

try{
    tx = em.getTransaction();
    tx.begin();

    q = em.createNamedQuery("Profile.getRandomProfile");
    q.setParameter("random", Math.random());
    q.setMaxResults(8);
    list = (List<Profile>) q.getResultList();

    if (list != null){
        Collections.shuffle(list);
    }

    tx.commit();

} catch(NoResultException ex){
    System.out.println("ERROR CATCHED: " +ex.getMessage());
    if(tx != null && tx.isActive())
        tx.rollback();
} catch(Exception e){
    e.printStackTrace();
}
finally{
    em.close();
}

洗牌有错误:

java.lang.UnsupportedOperationException: Query result sets are not modifiable

如何克服这个问题?

将结果复制到辅助列表并将其混洗,而不是查询结果列表。

ArrayList copyList = new ArrayList();
Collections.copy(copyList,list);
Collections.shuffle(copyList);

在线

list = (List<Profile>) q.getResultList();

在它之后,你应该根据结果创建一个新列表,如下所示:

 List<Profile> anotherList= new ArrayList<Profile>(listaOrdenes);

这样你就有了一个“新”列表,你可以修改它。

也许是这样的?

List<Profile> profiles = null;
List<Profile> results = (List<Profile>) q.getResultList();
if(results != null) {
    profiles = new ArrayList<Profile>();
    profiles.addAll(results);
    Collections.shuffle(profiles);
}

就像其他两个人说的那样,你应该将结果复制到你自己的列表中,因为它们以只读模式返回。 另一种可能性是返回的List实现不支持shuffle调用的操作。 您还可以尝试查看要验证的列表类型,但我怀疑是这种情况。

有两种选择:

1)创建新列表(2)在查询中使用ORDER BY子句。

Collections.sort(...)将对您提供的列表进行排序。 因此,它将修改列表。 但是,您尝试排序的列表是不可修改的。 当Collections.sort(...)调用列表中的一个方法来添加或删除元素时,它将引发异常。

一种解决方案是从原始列表创建新的可修改列表,然后对该列表进行排序。

// Create a new ArrayList that contains all elements from the list 'identities'
List<Identity> data = new ArrayList<Identity>(identities);

// Sort the new list

Collections.sort(data);

但是,由于您可能使用JPA查询从数据库中获取列表,因此最好将数据库查询更改为包含“order by”子句 ,以便让数据库进行排序。 您不需要在Java代码中进行排序。

暂无
暂无

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

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