Search code examples
javahibernatejpapersistence

How to query list elements using spring JPA


Context: Salad contains multiple vegetables. Lets assume that recipe of the salad is to add vegetables in the given order so the order also needs to be persisted

Here are the class definitions

public class Salad {
  private String name;
  private String description;
  private List<Vegetable> veggies = new ArrayList<Vegetable>();
  //setters and getters
}

public class Vegetable {
 private String name;
 private String description;
 //setters and getters
}

Here is the hibernate-mapping.xml

<hibernate-mapping>
    <class name="Salad" table="SALAD">
        <id name="id">
            <generator class="sequence"/>
        </id>
        <property name="name"/>
        <property name="description"/>
        <list name=veggies cascade="all-delete-orphan" table="SALAD_VEGGIES" lazy="false">
          <key column="salad_id" />
          <list-index column="idx" />
          <many-to-many column="veg_id" class="Vegetable" />
        </list>
    </class>
    <class name="Vegetable" table="VEGETABLE">
        <id name="id">
            <generator class="sequence"/>
        </id>
        <property name="name"/>
        <property name="description"/>
    </class>
</hibernate-mapping>
  1. I am using the List because sequence of the vegetables have to preserved
  2. When saving the salad, constituent vegetables already exists in the Vegetables table

Objective: Create a JPQ query to fetch the list of all the vegetables involved for a given salad

What I tried? 1)

SELECT v FROM SALAD.veggies v where v.salad_id = :salad_id

which didn't work. How to query on a table that doesn't have a class (like List and Map? variables)


Solution

  • Try this:

    SELECT v FROM Salad s JOIN s.veggies v where s.id = :salad_id
    

    Remember: in JPQL you work with Java fields, not with column names. Also there is not relationship from Vegetable entity to the Salad entity.