Search code examples
sqljpanetbeansglassfishpersistence

What's wrong with this Java Persistence query?


I would like to create an query which will give me the data with the object type Organisatie.

This is what I have so far

public List<Organisatie> findAll() {
        return em.createQuery("SELECT c FROM Contact c WHERE c.naam LIKE :custName").setParameter("custName","ORGANISATIE").getResultList();
    }

The command works but my list is empty ? Any ideas ? thanx

::EDIT1:: Sorry wrong copy paste. This is the query which I use

public List<Organisatie> findAll() {
    return em.createQuery("SELECT c FROM Contact c WHERE c.dtype LIKE :type").setParameter("type","ORGANISATIE").getResultList();

To give more information: I have an table which is called Contact. It's an abstract class. The class Organisation and Person inherit from that class.

For some reason I cannot make a select directly from Organisation or Person. That is why I'm trying it this way...Hope this clearify's my problem!

::EDIT2::

Farheq his query first did not work. But actually the query was correct! It was the Object Type of the list which had to be changed, not List but List. So the correct method follows :

@GET
@Produces({"application/xml", "application/json"})
@Override
public List<Contact> findAll() {
    return em.createQuery("SELECT c FROM Contact c WHERE c.dtype LIKE :type").setParameter("type", "%Organisatie%").getResultList();
}

Solution

  • Since you have used like operator, I think for sure you didn't mean = operator, I think you want to retrieve contacts which their naam contains ORGANISATIE so put your value inside % %:

    em.createQuery("SELECT c FROM Contact c WHERE c.naam LIKE :custName")
    .setParameter("custName","%ORGANISATIE%")
    .getResultList();
    

    Also above JPQL query is returning a list of Contact but the findAll() method returns List<Organizatie>, it is required the returning collection by getResultList() should be compatible with return type of the method, in this case you may change the select to select Organizatie objects or change the return type of the method to List<Contact> or depend on your entities you may convert the returned collection by above query by using (List<Contact>) if is convertible to it.