I get following error: "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'Card.findPrefix'"
for:
#NamedNativeQueries({
#NamedNativeQuery(name = "Card.findPrefix",
query = "SELECT DISTINCT(FLOOR(c
.number/10000)) FROM Card c")
})
public List<Integer> findPrefix(){
Query q = em.createNativeQuery("Card.findPrefix");
try{
return q.getResultList();
}catch(Exception ex){
ex.printStackTrace();
return null;
}
}
I can not understand where is my mistake, because when I type this query directly to Mysql it works perfectly.
Use should use createNamedQuery, instead of createNativeQuery.
From EntityManager JavaDoc
createNativeQuery(String sqlString)
Create an instance of Query for executing a native SQL statement, e.g., for update or delete.
createNamedQuery(String name)
Create an instance of Query for executing a named query (in the Java Persistence query language or in native SQL).
So in your code you are executing query name 'Find....' as SQL query.
The right one:
Query q = em.createNamedQuery("Card.findPrefix");
Final code is:
public List<Integer> findPrefix(){
Query q = em.createNamedQuery("Card.findPrefix");
List<Integer> res = new ArrayList<Integer>();
for(Object row : (List<Object>) q.getResultList()){
res.add(((BigInteger)row).intValue());
}
return res;
}
#NamedNativeQueries({
#NamedNativeQuery(name = "Card.findPrefix",
query = "SELECT DISTINCT(FLOOR(c.number/10000)) FROM Card c")
})
Related
Am upgrading Hibernate from 5.1.2.Final to 5.4.13. Am facing issue in below code,
#Entity
#NamedNativeQuery(name = "getStudentDetails", resultClass = StudentEntity.class, query = "{call getStudentDetails(?)}")
public class StudentEntity {
private Long id;
private String name;
}
and my DAO class like below,
public List<StudentEntity> getStudentDetails(){
List<StudentEntity> result = null;
try{
Query query = em.createNamedQuery("getStudentDetails");
result = query.getResultList();
}catch(Exception e){
}
return result;
}
create or replace procedure getStudentDetails(p_return_cur OUT SYS_REFCURSOR) is Store procedure with only output parameter.
am not set outparameter in java code. Till Hibernate 5.2.* don't have this issue. When update to 5.3.* it return "ordinal parameter not bound 1".
Positional Parameters are not Supported since 5.3
Support for legacy-style query parameter ('?') declarations in HQL/JPQL queries has been removed. This feature has been deprecated since Hibernate 4.1 and finally removed in 5.3 version.
Therefore, the following query declaration is not valid:
Query<Product> query = OBDal.getInstance().getSession()
.createQuery("from Product as p where p.name = ? and p.stocked = ?", Product.class);
query.setParameter(0, "Ale Beer");
query.setParameter(1, true);
To make the previous query work fine it must use named parameters:
Query<Product> query = OBDal.getInstance().getSession()
.createQuery("from Product as p where p.name = :name and p.stocked = :isStocked", Product.class);
query.setParameter("name", "Ale Beer");
query.setParameter("isStocked", true);
Code sample is taken from http://wiki.openbravo.com/wiki/Hibernate_5.3_Migration_Guide
when i run my query in database visualizer its working perfectly, but i think there are some issues in syntax when i convert it in my DAO class method.
I want to get whole data against the name provided
In Visualizer:
SELECT first_name,last_name,nic,phone,email FROM x_hr_user where (first_name = 'Irum');
Now in Dao
public List<XHrUser> findXHrUserByNameInTable()
{
String name ="Irum";
Query query = em.createQuery("SELECT xHrNewUserObj.firstName,xHrNewUserObj.lastName, xHrNewUserObj.nic, xHrNewUserObj.phone, xHrNewUserObj.emil FROM XHrUser xHrNewUserObj where (xHrNewUserObj.firstName) = (name)");
List<XHrUser> list = query.getResultList();
return list;
}
Instead of showing single row, it displays whole data Table
Thank you
Your current query is not valid JPQL. It appears that you intended to insert the raw name string into your query, which could be done via a native query, but certainly is not desirable. Instead, use a named parameter in your JPQL query and then bind name to it.
String name = "Irum";
Query query = em.createQuery("SELECT x FROM XHrUser WHERE x.firstName = :name")
.setParameter("name", name);
List<XhrUser> list = query.getResultList();
You have to write query as below. where : is used for variable
Query query = em.createQuery("SELECT xHrNewUserObj.firstName,xHrNewUserObj.lastName, xHrNewUserObj.nic, xHrNewUserObj.phone, xHrNewUserObj.emil FROM XHrUser xHrNewUserObj where (xHrNewUserObj.firstName) = :name");
I would like to set parameter to a native query,
javax.persistence.EntityManager.createNativeQuery
Something like that
Query query = em.createNativeQuery("SELECT * FROM TABLE_A a WHERE a.name IN ?");
List<String> paramList = new ArrayList<String>();
paramList.add("firstValue");
paramList.add("secondValue");
query.setParameter(1, paramList);
Trying this query result in Exception:
Caused by: org.eclipse.persistence.exceptions.DatabaseException:
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server
version for the right syntax to use near
'_binary'??\0♣sr\0‼java.util.ArrayListx??↔??a?♥\0☺I\0♦sizexp\0\0\0☻w♦\0\0\0t\0
f' at line 1
Error Code: 1064
Call: SELECT * FROM Client a WHERE a.name IN ?
bind => [[firstValue, secondValue]]
Query: ReadAllQuery(referenceClass=TABLE_A sql="SELECT * FROM TABLE_A a WHERE a.name IN ?")
Is it any way to set list parameter for native query, without cast to string and append it to sql query?
P.S. I'm use EclipseLink 2.5.0 and MySQL server 5.6.13
Thanks
I believe you can only set list parameters to JPQL queries, not native queries.
Either use JPQL, or construct the SQL dynamically with the list.
It works if you name the parameter:
Query query = em.createNativeQuery("SELECT * FROM TABLE_A a WHERE a.name IN (:names)");
List<String> paramList = new ArrayList<String>();
paramList.add("firstValue");
paramList.add("secondValue");
query.setParameter("names", paramList);
Not a solution but more of a workaround.
Query query = em.createNativeQuery("SELECT * FROM TABLE_A a WHERE a.name IN ?");
List<String> paramList = new ArrayList<String>();
String queryParams = null;
paramList.add("firstValue");
paramList.add("secondValue");
query.setParameter(1, paramList);
Iterator<String> iter = paramList.iterator();
int i =0;
while(iter.hasNext(){
if(i != paramList.size()){
queryParams = queryParams+ iter.next() + ",";
}else{
queryParams = queryParams+ iter.next();
}
i++;
}
query.setParameter(1, queryParams );
You can add multiple values like this example:
TypedQuery<Employee> query = entityManager.createQuery(
"SELECT e FROM Employee e WHERE e.empNumber IN (?1)" , Employee.class);
List<String> empNumbers = Arrays.asList("A123", "A124");
List<Employee> employees = query.setParameter(1, empNumbers).getResultList();
Source: PRAGT E., 2020. JPA Query Parameters Usage. Retrieved from: https://www.baeldung.com/jpa-query-parameters
I'm trying to fetch the last entity that was inserted into the database, which I thought would be a very simple thing to do, but every query i try results in some sort of exception to get thrown
The code im using is:
#Override
public DataStoreMark getLastMark() {
String selectQuery = "from Mark";
Query query = em.createNativeQuery(selectQuery, DataStoreMark.class);
try {
return (DataStoreMark) query.getSingleResult();
} catch (NoResultException e) {
log.error("Couldn't find any Marks in the DataStore.");
}
return null;
}
This code however throws a PesistenceException:
org.hibernate.exception.SQLGrammarException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from milestone' at line 1
And there is definitely a record in the database.
Any ideas?
You can use either of createQuery() and createSqlQuery() if it does not work:
1.
String selectQuery = "from Mark";
Query query = em.createQuery(selectQuery);
return (DataStoreMark) query.list().get(0);
2.
String selectQuery = "select * from Mark";
SQLQuery query = (SQLQuery) em.createSQLQuery(selectQuery);
query.addEntity(DataStoreMark.class);
return query.list();
I think hibernate does not tell about last entity added to the database. Alternatively you can write the query specific to your db and run it using createSqlQuery() as shown above.
Actually I had one SQL query that runs very fine with mySql database. but, my problem is that I want to write that query in hibernatetemplate query.
My SQL QUERY IS
SELECT * FROM task, dependency WHERE DEPENDENCY_From IN(10,11,12,13)
and I want it to executed by the hibernate template.
How do I to convert this to a HibernateTemplate Query?
If you want to use HibernateTemplate query then below is example of hibernate query but in your case, we need mapping files to see how the entities are associated. Hope below query will help you.
public List<Object[]> getCities(Integer stateId) {
List<Object[]> cityList = new ArrayList<Object[]>();
String query = "select city.cityId,city.cityName from City city where city.state.stateId=?";
Object[] queryParam = {stateId};
cityList = getHibernateTemplate().find(query, queryParam);
return cityList;
}
or
String query="from City";
List<City> cityList = getHibernateTemplate().find(query);
HQL query
Object[] params = {cid,cid};
List list=getHibernateTemplate().find("select S.stateName,C.countryName from State S,Country C where C.countryId=? and S.countryId=?", params);
SQL Query
select S.stateName,C.countryName from State S,Country C where S.countryId=C.countryId;