Mariusz
Mariusz

Reputation: 1985

unexpected end of subtree

I use JPA with hibernate. I want to check that row with specified name and username exists. The following query raises an error:

@Query("select exists (select 1 from Strategy s where s.name=:name and s.username=:username)")
Boolean exists2(@Param("name") String name,@Param("username") String username);

Error:

Caused by: org.hibernate.hql.ast.QuerySyntaxException: unexpected end of subtree [select exists (select s from com.soft.domain.strategy.Strategy s where s.name=:name and s.username=:username)]

Any ideas?

Upvotes: 3

Views: 9658

Answers (3)

Same issue here. It seems it's impossible. So the solution is to use a native query.

@Query(value = "select exists (select 1 from Strategy s where s.name=:name and s.username=:username)", nativeQuery = true)

Assuming your Strategy entity is mapped to a table named Strategy (if you're using another name, change it accordingly in the query).

The trade off is that your query becomes database dependent, but I believe for the exists clause it works the same way in almost all databases, so you're not supposed to face issues if you change from Postgre to MySQL for example.

If native queries really bother you, the count approach gives you want you want, but be aware it's less efficient since it goes through all records in your table, while the exists approach stops when it finds the first record.

Upvotes: 0

Mariusz
Mariusz

Reputation: 1985

I solved this problem by switching query on the following:

@Query("select count(s) from Strategy s where s.name=:name and s.username=:username")
long exists2(@Param("name") String name, @Param("username") String username);

Upvotes: 1

romeara
romeara

Reputation: 1506

Did you put the ":name" and ":username" back in yourself in place of example values, or is that the exact error message you received? If that is the exact message, then it appears your named parameters are not being substituted. I don't have much experience with this particular usage of hibernate, but somewhere to start would be to investigate the use of named parameters in conjunction with the @Query annotation. (Unfortunately the exception does not make this clear from the outset)

Upvotes: 0

Related Questions