Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPQL ManyToMany select

I have a Many To Many relationship between two entities called: Car and Dealership.

In native MySQL I have:

car (id and other values)
dealership (id and other values)
car_dealership  (car_id and dealership_id)

And the query I want to make in JPQL is:

#Select List of cars in multiple dealerships
SELECT car_id FROM car_dealership WHERE dealership_id IN(1,2,3,56,78,999);

What is the proper way to make the JPQL equivalent?

My Java method signature is:

public List<Car> findByDealership(List<Dealership> dealerships);

I have tried

    //TOTALLY WRONG QUERY CALL!!!     
    Query query = em.createQuery("SELECT c FROM Car c WHERE :dealer_ids IN c.dealerships");
    List<Long> dealerIds = new ArrayList<Long>();
    for(Dealership d : dealerships) {
        dealerIds.add(d.getId());
    }
    query.setParameter(":dealer_ids", dealerIds); 
    List<Dealership> result = (List<Dealership>) query.getResultList();
    return result;
}

Here is my JPA Annotations for such relationship in java:

@Entity
@Table(name = "car")
public class Car implements Serializable {

     //Setup of values and whatnot....
     @ManyToMany
     @JoinTable(name = "car_dealership", joinColumns =
     @JoinColumn(name = "car_id", referencedColumnName = "id"),
     inverseJoinColumns = @JoinColumn(name = "dealership_id", referencedColumnName = "id"))
     private List<Dealership> dealerships;

     ... other stuff (getters/setters)

}

@Entity
@Table(name = "property")
public class Dealership implements Serializable {

    //Setting of values and whatnot

    @ManyToMany(mappedBy = "dealerships")
    private List<Car> cars;

    .... other stuff(getters/setters)

}

EDIT

I also have tried:

 Query query = em.createQuery("SELECT c FROM Car c INNER JOIN c.dealerships d WHERE d IN (:deals)");
 query.setParameter("deals", dealerships);

Which threw the Error:

org.eclipse.persistence.exceptions.QueryException

Exception Description: Object comparisons can only use the equal() or notEqual() operators.  
Other comparisons must be done through query keys or direct attribute level comparisons. 

Expression: [
Relation operator [ IN ]
Query Key dealerships
  Base stackoverflow.question.Car
Constant [
Parameter deals]]
like image 217
gtgaxiola Avatar asked Sep 14 '12 13:09

gtgaxiola


People also ask

Can we use subquery in JPQL?

A subselect is a query embedded into another query. It's a powerful feature you probably know from SQL. Unfortunately, JPQL supports it only in the WHERE clause and not in the SELECT or FROM clause. Subqueries can return one or multiple records and can use the aliases defined in the outer query.

What is JPQL vs SQL?

SQL works directly against relational database tables, records and fields, whereas JPQL works with Java classes and instances. For example, a JPQL query can retrieve an entity object rather than field result set from database, as with SQL. The JPQL query structure as follows. SELECT ...

Is HQL and JPQL same?

The Hibernate Query Language (HQL) and Java Persistence Query Language (JPQL) are both object model focused query languages similar in nature to SQL. JPQL is a heavily-inspired-by subset of HQL. A JPQL query is always a valid HQL query, the reverse is not true however.

Why JPQL is better than SQL in Web application?

JPA allows you to avoid writing DML in the database specific dialect of SQL. JPA allows you to load and save Java objects and graphs without any DML language at all. When you do need to perform queries JPQL allows you to express the queries in terms of the Java entities rather than the (native) SQL tables and columns.


1 Answers

select car from Car car 
inner join car.dealerships dealership
where dealership in :dealerships

The parameter must be a collection of Dealership instances.

If you want to use a collection of dealership IDs, use

select car from Car car 
inner join car.dealerships dealership
where dealership.id in :dealershipIds

Remamber that JPQL always use entities, mapped attributes and associations. Never table and column names.

like image 135
JB Nizet Avatar answered Oct 17 '22 22:10

JB Nizet