Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityManager#getResultList() returns an empty list

Tags:

jpa

jpql

I'm working on my first web shop and have trouble to retrieve objects when searching for them. Searching for an existing product results in that the list productHits remains empty.

(To read the whole project please see https://github.com/gitsjogren/TareaWebShop)

Here's the product catalogue:

public final class ProductCatalogue extends AbstractDAO<Product, Long> implements IProductCatalogue {

    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("shop_pu");
    private static Product p1;
    private static Customer c1;

@Override
    public List<Product> search(String searchWord){
        EntityManager em = emf.createEntityManager();
        List<Product> prodHits = new ArrayList<>();
        try {
            String sqlQuery = "SELECT p FROM Product p WHERE p.name LIKE :theSearch";
            TypedQuery<Product> q = em.createQuery(sqlQuery, Product.class);
            String searchQuery = "%" + searchWord + "%";
            q.setParameter("theSearch", searchQuery);
            prodHits = (List<Product>) q.getResultList();
        } catch (Exception e) {
            System.out.print(e);
        }
        em.close();
        return prodHits;
}    

I have also tried using a NativeQuery instead of a TypedQuery, with no luck.

Query q = em.createNativeQuery(sqlQuery, Product.class);
like image 589
user3033861 Avatar asked Jun 09 '26 04:06

user3033861


1 Answers

If you're didn't get your answer yet:

it can happen when you have something uncommitted on that table in DB. In that case, if you run the same query in DB you'd get the real answer, but if you run it from the code, it may return empty list.

like image 196
Armine Avatar answered Jun 10 '26 19:06

Armine



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!