Pergunta

Using JPA/Eclipse TopLink.

I'm updating a table (using createNativeQuery) as shown below:

Query query = em.createNativeQuery("UPDATE Products SET productName='" + p.getProductName() + "',productVendor='" + p.getProductVendor() + "',productDescription='" + p.getProductDescription() + "',quantityInStock=" + p.getQuantityInStock() + ",buyPrice =" + p.getBuyPrice() + ",msrp=" + p.getMsrp() + " WHERE productCode='" + p.getProductCode() + "'");
query.executeUpdate();

The update is reflected in the DB (MySQL)

For retrieving (using createQuery) as show below:

Query query1 = em.createQuery("SELECT p from Products p where p.productCode='"+searchTerm+"'");
return query1.getResultList();

However, the ResultList returned is always the data before the update. But when I use the createNativeQuery instead of createQuery the latest updated data is returned. What could the possible error be with createQuery method?

Foi útil?

Solução

when you use batch update or native queries, you're bypassing the first-level cache. Toplink has no way to know that the entities it already has in its first-level cache have been changed. So the entity manager must be cleared in order for the query to retrurn refreshed objects.

But the best way is probably to avoid batch updates in the first place. Your first query could be replaced by a JPQL query that loads the product with the given code, and then simply updates the Product entity. Even if you keep the update query, it could be written in JPQL rather than SQL (but you would still have the problem you're having).

Finally, your queries should use parameters to avoid injections and make sure everything is properly escaped:

Query query1 = em.createQuery("SELECT p from Products p where p.productCode = :searchTerm);
query1.setParameter("searchTerm", searchTerm);
return query1.getResultList();
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top