Vinayak Raikar
Vinayak Raikar

Reputation: 31

JPQL org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: union near line 1

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
@Repository
public interface SearchRepository extends 
         PagingAndSortingRepository<CPAttribute, Long>
{
    @Query("select cpa.cpAttributeId from CPAttribute cpa " +
    " union " +
    " select cps.cpGroupId from CustPro cps")
    Page<CustProProjection> findBySerial(Pageable pageable);
}

I'm trying to get the set of data from two different tables using spring data JPQL custom query union operator. Its a spring boot application calling the repository code. The code shown above compiles but while running the server it gives the error

org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: union near line 1
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: union near line 1.

Jars used:
spring-data-jpa-2.0.6.RELEASE.jar
spring-data-commons-2.0.6.RELEASE.jar
spring-orm-5.0.5.RELEASE.jar

The code throws an error for union operator. Can anybody suggest how to resolve this error?

Upvotes: 3

Views: 5308

Answers (1)

Jens Schauder
Jens Schauder

Reputation: 81990

As ali akbar azizkhani wrote in the comments: There is no UNION keyword in JPQL. The straightforward approach would be to use a native SQL statement instead.

Alternatively, one might make the two queried entities into a type hierarchy and arrive at a similar result by querying the supertype. Although, in general, I'd advice against relying on inheritance since it creates some considerable additional complexity.

Upvotes: 4

Related Questions