简体   繁体   中英

JPQL query with some logic

I was just wondering if it's possible to create a JQPL query that would go throgh the table and select all records that match at least x ouf of y properties on the object I'm passing to the query. Imagine Car object with 5 properties: maxSpeed, weight, colour, power, type and then I want to query a database to get all cars that have at least 2 properties the same as the car I'm passing to the query (not the actual car - just its properties). I wasn't able to find anything so I'm just getting all entries that have at least one property matching (by using 4 'OR' operators in my query) and then process the result list in Java. There must be a way of doing this just by using JPQL, I would be grateful for any hints. The query I am using so far looks like this:

TypedQuery<Car> query = em.createQuery(
                "FROM Car c "
                + "WHERE c.maxSpeed = :maxSpeed "
                + "OR c.weight = :weight "
                + "OR c.colour = :colour "
                + "OR c.power = :power "
                + "OR LOWER(c.type) = LOWER(:type)"
            , Car.class);
        query = query.setParameter("maxSpeed ", car.getMaxSpeed ());
        query = query.setParameter("weight ", car.getWeight());
        query = query.setParameter("colour", car.getColour());
        query = query.setParameter("power", car.getPower());
        query = query.setParameter("type", car.getType());
query.getResultList()

I did not test it but maybe you could use a construct with JPQL case statements like this:

WHERE (CASE c.maxSpeed WHEN :maxSpeed THEN 1 ELSE 0 END
     + CASE c.weight WHEN :weight THEN 1 ELSE 0 END
     + CASE c.colour WHEN :colour THEN 1 ELSE 0 END
     + CASE c.power WHEN :power THEN 1 ELSE 0 END
     + CASE LOWER(c.type) WHEN LOWER(:type) THEN 1 ELSE 0 END) > 1

Each case statement returns either 0 or 1. If the total is greater than one then the condition is met.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM