My Spring JPA queries do not work with H2 - java

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.

Related

How to convert a select statement in mysql into a query in java?

I have a select statement inside MySQL.
select * from tbl_user where path like '%,id,%'
How can I convert it to a query in Java? What I want to pass id.
maybe
#Query(value = "select * from tbl_user where path like CONCAT('%,',?1,',%')", nativeQuery = true)
Iterable<Tbl_user> findAllChildUsers(int id);
will help
It depends of what framework/library are you using.
in hibernate you can use :id, but you have to also check that it is native query.
In some libraries you just pass a String as a query.

Spring Boot doesn't work custom JPA request

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

Major performance degradation with named parameters and preventing sql injection using hibernate with native sql

I'm using hibernate 3.6.4.Final and sql server 2008 r2 and got a query on a table with more than 20 million records. Criteria api does unfortunatly generate sub-optiomal queries when paging (select top 100010 from ... for result 100000 - 100010 ) when using firstResult / maxResult so I've reverted to native sql.
This queries run blazingly fast in sql studio but using named or positional parameters in hibernate those queries crawl painfully slow. Googling along I couldn't find any solution so I'm currently concatenating parameters which allows sql injections, but this is of course no option for production!
Now I'm wondering if there's something I've overlooked or at least some hibernate api or library I'm not aware of which I could use to sanitize parameters before rolling my own and probably failing to catch some edge case...
Unfortunately, Criteria API is the best way to avoid sql injection, but it is so slow, the best way is to use normal Hibernate Queries with dynamic parameters, i mean For ex:
String stringQuery ="select * from User as u where id = :id";
Query query=session.createQuery(stringQuery);
query.setParameter("id",12);
OR u can make your query more dynamic by creating a new Class MyQueryBuilder
public class myQueryBuilder(){
public Query buildQuery(int id){
String stringQuery ="select * from User as u where u.id = :id";
Query query=session.createQuery(stringQuery);
query.setParameter("id",12);
return query;
}
public Query buildQuery(int id,String name){
String stringQuery ="select * from User as u where u.id = :id and u.name = :name";
Query query=session.createQuery(stringQuery);
query.setParameter("id",12);
query.setParameter("name",name);
return query;
}
...
//Later you can call the query builder methods as you want depending on your params
}
and remember that it is always safe using setParameter() Method

How to get count using JPA

I am writing very simple native query in JPA, it is executing in oracle if I run it directly but failed when run trough JPA.
String sql = "select count(*) from demo.sb_test_config cf, isisdba.sb_transpoter st where cf.policy_id = st.policy_id " +
"and cf.payment_type = 'PAID' and st.sb_t_id = :tId" ;
Query query = em.createNativeQuery(sql);
query.setParameter("tId", 8);
Long response = (Long)query.getSingleResult();
Can some help to find the root cause. What I missing while executing JPA.
Thanks in advance
How does it fail in JPA?
I can see that you are attempting to use old SQL join syntax to get data from two different schemas - is JPA set to allow you to do that?
You did not even say how your attempts fail...

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