Spring Boot doesn't work custom JPA request - java

Having this code:
#Query(value = "SELECT t FROM trainings t ORDER BY RANDOM() LIMIT 8", nativeQuery = true)
List<Training> findRandom();
Getting this error:
org.postgresql.util.PSQLException: The column name id was not found in this ResultSet.
When executing this code:
System.out.println(trainingRepo.findRandom());
Where is my problem? How can I solve it?

You don't need to use "t" here because it's not JPQL but native query (you've set nativeQuery = true)
Replace the query with SELECT * FROM trainings ORDER BY RANDOM() LIMIT 8

Related

My Spring JPA queries do not work with H2

This query below does not work and it generates me an exception
#Query(value = "SELECT * FROM account WHERE account_no = ?1",
nativeQuery = true)
Account findByAccountNo(String accountNo);
"message": "could not prepare statement; SQL [SELECT * FROM account WHERE account_no = ?]; nested exception is org.hibernate.exception.SQLGrammarException: could not prepare statement",
When I used the MySQL database, the query worked fine. But now that I am using the H2 database, it suddenly does not work. Why? How do I fix this?
It would be better to use JPA.
If you still wanna use nativeQuery, use like this:
#Query(value = "SELECT * FROM account WHERE account_no = :account_no",
nativeQuery = true)
Account findByAccountNo(#Param("account_no") String accountNo);
I'm guessing here, but the parameter syntax "?1" probably is not valid for H2.
There's no need to use a native query here, and if you use Jpa syntax instead, it should work.
Also, you shouldn't need to specify a query here at all - Spring Jpa should generate the query for you.

Hibernate : How to get last n rows in spring boot JpaRepository?

Iam working with spring boot and jpa repository I want get the last 2 records from database using hql query.
I have writen the follwoing query but its not working.
#Query("select news from(select news from NewsDTO news order by news.newsId desc limit 2) sub order by news.newsId asc")
It is throwing the folloing exception
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 17 [select news from(select news from com.mer.aigs.dto.news.NewsDTO news order by news.newsId desc limit 2) sub order by news.newsId asc]
JPQL doesn't support LIMIT clause natively. With Spring Data JPA, however, you can use
combination of ORDER BY .. DESC and Pageable to achieve what you intend to. Refer this for detailed information https://www.logicbig.com/tutorials/spring-framework/spring-data/pagination.html
limit keyword is not supported by hql (it's even different across different databases). You need to create a Query using entity manager and specify the maximal size:
em.createQuery("your query").setMaxResults(2).getResultList()
assuming you have entity manager injected:
#Autowired
private EntityManager em
This solution performs better than using Pageable.
As mentioned by #Kedar you cannot use LIMIT inside your JPQL query due to the database-specific nature. Therefore you need to use a NATIVE QUERY and replace the physical table name and column name for NewsDTO and newsId:
#Query(value = "select news from(select news from *NewsDTO* news order by *newsId* desc limit 2) sub order by *newsId* asc", nativeQuery = true)
This worked for me, where created is the timestamp column in the table:
repository.findAll(PageRequest.of(0, 2, Sort.by("created").descending())))
In my case, I wanted the result sorted by the created column.
Hope this helps someone.

Convert sql query to hql

SELECT recipe.name,SUM(salesdetails.quantity::integer),recipe.price As Quantity
FROM (salesinfo JOIN salesdetails ON salesinfo.sessionid=salesdetails.salesinfo_sessionid)
JOIN recipe ON salesdetails.recipe_id=recipe.id group by salesdetails.recipe_id,recipe.name,recipe.price
ORDER BY SUM(salesdetails.quantity::integer) DESC;
Can anyone give me the hql query for this?
If you are not acquainted with the HQL and want to use the same query ,then you can do it using the native query feature of the Hibernate like this :
#QUERY(value="SELECT recipe.name, SUM(salesdetails.quantity::
INTEGER),recipe.price AS Quantity
FROM (salesinfo
JOIN salesdetails ON salesinfo.sessionid=salesdetails.salesinfo_sessionid)
JOIN recipe ON salesdetails.recipe_id=recipe.id
GROUP BY salesdetails.recipe_id,recipe.name,recipe.price
ORDER BY SUM(salesdetails.quantity:: INTEGER) DESC", nativeQuery = TRUE)
But I would recommend that you first try to convert the same in into HQL query and then if any issue then you should ask it here instead of directly asking for the converted query. Meanwhile this can help.

Parameter in SELECT clause for #Query?

While using a verbatim entered column name works fine in an SQL/JPA query, is it possible to use a variable?
#Query(value = "select distinct ?1 from Product", nativeQuery = true)
List<String> findOneColumn(String columnName);
This code appears to fail. It seems that it's not allowed to use parameters in SELECT clause (but works with WHERE clause). Is there any alternatives?
How can I set the column name dynamically?
Seems that Parameter in SELECT clause for #Query is not allowed pleasure :)

Executing hibernate template's findByNamedQuery

I'm pretty new to hibernate and I was trying it out in one of my applications. I chose to use annotation session factory bean and my editor generated entity classes for each table from the DB which had named queries. hibernateTemplate.findByAll worked fine. But when I tried hibernateTemplate.findByNamedQuery("findById", "<some_id>"), it gave an error: java.lang.IndexOutOfBoundsException: Remember that ordinal parameters are 1-based. After a bit of googling, tried out multiple solutions:
Changed the namedQuery that was generated by editor from : #NamedQuery(name = "Table.findById", query = "SELECT u FROM Table t WHERE t.id = :id"), to : #NamedQuery(name = "Table.findById", query = "SELECT u FROM Table t WHERE t.id = ?") but got the same error.
Tried using hibernateTemplate.findByNamedParam but ended up getting error: java.lang.IllegalArgumentException: node to traverse cannot be null!
I can use hibernateTemplate.find() to achieve this but how do I use findByNamedQuery/Param methods to achieve the same since the documentation says these methods may be used to fetch records based on a field?

Categories