简体   繁体   中英

Retrieving data from database using JPA

I am trying to get to grips with using JPA. And am extremely stuck. I am trying to retrieve data from a database to display on a form. I keep getting the following error and none of the information I have found online has helped:

java.util.ConcurrentModificationException

The code where the error occurs is below:

try
    {
        em.getTransaction().begin();
        Query q = em.createQuery("Select o from Order o");
        @SuppressWarnings("unchecked")
        List<Order> orders = q.getResultList();
        Iterator<Order> iterator = orders.iterator();
        while(iterator.hasNext())
        {
            Order order = (Order)iterator.next();

            order.setId(this.id);
            order.setCreated(this.created);
            order.setSender(this.sender);
            order.setReceiver(this.receiver);
            order.setInput(this.input);
            order.setOutput(this.output);
            order.setState(this.state);
            orders.add(order);
        }
        em.persist(orders);
        em.getTransaction().commit();
    }

You are looping through a list while adding to it which is causing the issue.

orders.add(order);

Create a new list and add orders to that, then persist that new list.

You can't add elements to a correction you're iterating over. (You're iterating over orders using orders.iterator(), and then you're trying to do orders.add(order) in the body of the iterator.)

The whole construct is useless anyway. Just change the properties of the objects in orders , and the changes will be saved to the database automagically when you commit() it. Last, but not least, you should use the extended for there.

for (Order order : (List<Order>) q.getResultList()) {
    order.setId(...);
    // ...
}
em.getTransaction().commit();

Going by the comments, you're just trying to retrieve existing records from the database, not add or modify anything in it. In that case, you just need to return the result of getResultList() to the GUI:

return (List<Order>) q.getResultList();

without doing anything else with the entity manager after that call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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