2

Given my SQL query below:

SELECT
  maker_code
FROM
  maker
WHERE
  part_no = p_part_no
AND effect_date_in <= TODAY
AND effect_date_out > TODAY 
AND effect_date_in = (SELECT MAX(effect_date_in) FROM maker WHERE part_no =p_part_no)

I want to use Spring Data JPA with inbuilt methods like findBy---() which will return the same result as of the above sql query

I tried JPQL Query:

 @Query(value = "
    SELECT p FROM Pg6p0012_01PurpartQueryModel p where p.partNo = :p_part_no AND 
    p.effectDateIn <= TODAY AND p.effectDateOut > TODAY AND p.effectDateIn = 
    (
    select max(p.effectDateIn)from Pg6p0012_01PurpartQueryModel where partNo =:p_part_no)"
    )

public List<Pg6p0012_01PurpartQueryModel>findByPartNo(@Param("p_part_no") String p_part_no);

But I am getting an error: Bad use of aggregate in this context.

6
  • 1
    And where is the question? Which part of the JPQL are you having a problem with? What have you tried? where is your error? Commented Dec 31, 2016 at 10:42
  • @ Neil Stockton I have edited the question Commented Dec 31, 2016 at 10:54
  • 2
    JPA API has no such "inbuilt functions" like "findBy...". Please read the JPA spec if you don't realise this. You are presumably referring to SPRING DATA JPA ... which is NOT the JPA API. Understand what technology you use first Commented Dec 31, 2016 at 10:55
  • Thats correct I am using SPRING DATA JPA. Is there any way to achieve the above result using SPRING DATA JPA inbuilt functions. Commented Dec 31, 2016 at 10:57
  • 1
    Even if there was a way, you would end up with a method name that would be 250-characters long, and you really don't want that. Automatic query generation from method names is fine for simple queries like findByName(). They're not fine, and not intended to be used for complex queries. Use any method name, and annotate it with @Query, where you would define a standard JPQL query. Commented Dec 31, 2016 at 10:59

1 Answer 1

1

You can't access alias p from nested query for aggregation function like MAX. Nested query has to have its own alias for table. Something like:

 @Query(value = "
    SELECT p FROM Pg6p0012_01PurpartQueryModel p where p.partNo = :p_part_no AND 
    p.effectDateIn <= TODAY AND p.effectDateOut > TODAY AND p.effectDateIn = 
    (SELECT MAX(p2.effectDateIn) FROM Pg6p0012_01PurpartQueryModel p2 WHERE partNo =:p_part_no)"
 )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.