How to pass parameter to #Query annotation with hql - spring

Here is my hql requete :
#Query("select a from Agent where a.visibility = true a order by a.id desc")
public Page<Agent> getAllAgents(Pageable pageable);
I want to select all agents that have visibility true.
In my Agent class a have Boolean visibility attribute with getVisibility and setVisibility functions. In my data base "visibility" stored as bit(1).
I tried a.visibility = 1, ... = '1', ...= 'TRUE', ...='true', ... is true. But i get this error :
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: a near line 1, column 74 [select a from com.GemCrmTickets.entities.Agent where a.visibility = true a order by a.id desc]
Any suggestions ? Thank you in advance.

Your query is not correct, you have an extra a between true and order by.... So the correct query would become like this
select a from Agent a where a.visibility = true order by a.id desc
Not sure if that fixes all your troubles. Check it out.

Change your query to this:
#Query("select a from Agent a where a.visibility = true order by a.id desc")
public Page<Agent> getAllAgents(Pageable pageable);

In your code, you have to write the Alice name of the table so add it.
#Query("select a from Agent a where a.visibility = true order by a.id desc")

Related

cant using "LIKE" in native query spring boot

I try to get orders of user by query :
#Query(value = "SELECT * FROM ORDERS WHERE USER_ID = ?1 AND CAST(CREATE_AT AS NVARCHAR(100)) LIKE ?2 OR CAST(GRAND_TOTAL AS NVARCHAR(100)) LIKE ?2 OR CAST(STATUS AS NVARCHAR(100)) LIKE ?2" , nativeQuery = true)
Page<Order> getOrdersByUserSearch(int userID, String searchS, Pageable pageable);
But it always return empty list. i run this code in SQL server and it work (?1 =2. ?2 = '2021-06-26').
If I try to change "NOT LIKE" instead of "LIKE" It run.
I dont want using query ( not native), Named query or specification method because it get more error.
Any advice?.
SQL like query requires % along with the value for a match. In case of ordered parameters in queries we can use:
#Query("SELECT m FROM Movie m WHERE m.rating LIKE ?1%")
List<Movie> searchByRatingStartsWith(String rating);
Click here for more info.
In your case the query string should be like this:
SELECT * FROM ORDERS WHERE USER_ID = ?1 AND CAST(CREATE_AT AS NVARCHAR(100)) LIKE %?2% OR CAST(GRAND_TOTAL AS NVARCHAR(100)) LIKE %?2% OR CAST(STATUS AS NVARCHAR(100)) LIKE %?2%

QuerySyntaxException occurred for JPA #Query for Distinct and Count

I am using the below as a JpaRepository interface method query
#Query("SELECT DISTINCT order.status, COUNT(*) FROM OrderEntity order WHERE order.customerNumber = ?1 GROUP BY order.status")
During app startup I am getting the following exception -
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: order near line 1, column 17 [SELECT DISTINCT order.status AS status, COUNT(*) AS count FROM debomitra.cmw.orders.entity.OrderEntity order WHERE order.customerNumber = ?1 GROUP BY order.status]
at org.hibernate.hql.internal.ast.QuerySyntaxException.convert(QuerySyntaxException.java:74)
at org.hibernate.hql.internal.ast.ErrorTracker.throwQueryException(ErrorTracker.java:93)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:297)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:189)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:144)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:113)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:73)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:155)
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:600)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:709)
... 116 more
Is there any other way to write DISTINCT/COUNT query in JPA or am I doing something wrong?
Please provide me with some pointers.
I think the query will work if you modify it like below-
SELECT DISTINCT OrderEntity.status, COUNT(*) FROM OrderEntity WHERE OrderEntity.customerNumber = ?1 GROUP BY OrderEntity.status
The issue is with the order keyword in the JPQL. It is expecting a "by" keyword after the "order".
Whoever is reading this try avoiding "order" keyword in a statement expect at the end where you really need to issue a ORDER BY statement.

Spring MVC, Select Special Columns in Native SELECT Query

this is my native SELECT Query in Repository
#Modifying
#Query(value = "SELECT * FROM tasks WHERE title LIKE '%Java%' ORDER BY id DESC ", nativeQuery = true)
List<Task> listAllTasks();
this works ok, but when I use custom column name instead of *, like this
#Modifying
#Query(value = "SELECT title FROM tasks WHERE title LIKE '%Java%' ORDER BY id DESC ", nativeQuery = true)
List<Task> listAllTasks();
I have this error :
org.postgresql.util.PSQLException: The column name id was not found in this ResultSet.
any Help?
The resultset doesn't have the "id" in it, you have to provide it.
You should change the way you are declaring your SQL:
SELECT t.title, t.id FROM tasks t WHERE t.title LIKE '%Java%' ORDER BY t.id DESC
Check out this sort example:Native Queries
Select * from Entity -> returns a List of Entity
Example:
#Query(select * from tasks)
List<Task> findAllTasks();
Select column from Entity -> returns a List of Types of the entity.
Example:
#Query(select t.title from tasks t)
List<String> findTitle_AllTasks();
title is of the type String
Select multiple columns from Entity -> returns an Object[] holding the data
Example:
#Query(select t.id, t.title from tasks t)
List<Object[]> findIdTitle_AllTasks();
So, you are retrieving String type data - title and asking to return a List of Task type. This is causing the problem. You can actually check the hibernate docs under HQL and JPQL to understand this.
Plus, you are doing a SELECT (DQL operation). #Modifying is rudimentary here as it is used for DML operations using Data JPA - UPDATE/DELETE.

Parse error: syntax error, unexpected 'F' (T_STRING), expecting ',' or ')'

`$data['top_argo'] = \DB::select( \DB::raw('select DISTINCT SUM(transaction.total) as total_argo, COUNT(transaction.id) as total_trans, users.name FROM transaction LEFT JOIN CUSTOMER ON customer.id = transaction.id_driver_fk LEFT JOIN users ON users.id = customer.id_user_fk WHERE id_customer_fk IS NOT NULL AND transaction.status = 'F' GROUP B`Y users.name ORDER BY SUM (transaction.total) DESC LIMIT 10'));
I need to run this query on my laravel, but I got an error like I said on the title. I'm new to laravel so can you help me?
Your query has lots of syntax errors. Don`t use double quotes without binding it a string.
data['top_argo'] = \DB::select( \DB::raw("select DISTINCT SUM(transaction.total)
as total_argo, COUNT(transaction.id) as total_trans, users.name FROM transaction
LEFT JOIN CUSTOMER ON customer.id = transaction.id_driver_fk
LEFT JOIN users ON users.id = customer.id_user_fk
WHERE id_customer_fk IS NOT NULL AND transaction.status = 'F' GROUP BY users.name ORDER BY SUM (transaction.total) DESC LIMIT 10"));
To fix the exception replace 'F' with \'F\'

How to write Order by expression in JPQL

PostgreSQL and MySQL offers to write expression into ORDER BY clause in SQL query. It allows to sort items by some column but the special values are on the top. The SQL looks like this one. ( works in Postgres )
select * from article order by id = 4, id desc;
Now I want to write it in the JPQL but it doesn't work. My attempt is:
#NamedQuery(name = "Article.special", query = "SELECT a FROM Article a ORDER BY ( a.id = :id ) DESC, a.id DESC")
This is JPA 1.0 with Hibernate driver. Application server throws this exception on deploy.
ERROR [SessionFactoryImpl] Error in named query: Article.special
org.hibernate.hql.ast.QuerySyntaxException: unexpected AST node: = near line 1, column 73 [SELECT a FROM cz.cvut.fel.sk.model.department.Article a ORDER BY ( a.id = :id ) DESC, a.id DESC]
at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:54)
Thanks a lot.
For a named query, (ORDER BY ( a.id = :id ) or ORDER BY (:id )) won't work as DSC/ASC can't be parametrized at run-time.
1) Dynamic way if ordering element varies at runtime.
String query = "SELECT a FROM Article a ORDER BY "+orderElement+" DESC, a.id DESC";
entityManager.createQuery(query).getResultList();
2) Static way in entity bean if ordering element is fixed.
Field level:
#OrderBy("id ASC")
List<Article> articles;
Method level:
#OrderBy("id DESC")
public List<Article> getArticles() {...};

Resources