Error while getting sql record using EntityManager - java

I am using EntityManager in spring boot app to get result from this query
select (c.data::jsonb)->>'employee_Id' as empId from employee e where e.dept ='employee' and (e.data::jsonb)->>'section_id' = '1235'
Its giving me correct output in PgAdmin but in java code
List resultList = em.createNativeQuery(str).setParameter(1, sectionId ).getResultList();
Giving error ERROR: syntax error at or near ":" its breaking at data::jsonb .How do handle this using EntityManager.

You need to CAST like CAST(c.data as jsonb)->>'product_id' from string to JSONB. However i would highly suggest that you don't use TEXT for your JSON type data.
ALTER TABLE employee ALTER COLUMN data TYPE JSON USING data::JSON;
`

Related

Set random seed on Postgres using hibernate

I'm not very familiar with Hibernate, but I need to set the random seed on a PostgreSQL database using Hibernate.
This is what I'm trying to run:
String seedSql = "select setseed(0.123)";
Query seedQuery = entityManager.createQuery(seedSql);
seedQuery.getSingleResult();
However, this query does not return any entity mapped by Hibernate, thus I'm receiving the following error:
org.hibernate.QueryException: No data type for node: org.hibernate.hql.internal.ast.tree.MethodNode (...)
Any suggestions?
According to the docs, createQuery() takes a JPQL string, and apparently doesn't know what to do with your Postgres function call.
To run an SQL query, use createNativeQuery() instead.
After some trial and error I noticed that I had to use .createNativeQuery() since setseed() is a function from PostgreSQL:
String seedsql = "select cast(setseed(0.123) as text)";
Query seedQuery = DatabaseInterface.getEm().createNativeQuery(seedsql);
seedQuery.setMaxResults(1).getSingleResult();
I used cast(setseed(0.123) as text) to avoid another error:
org.hibernate.MappingException: No Dialect mapping for JDBC type: 1111

Hibernate - unexpected token: lower

I have to get all registers in my DB (PostgreSQL) with case-insesitive. I have tried with criteria but the ignoreCase() is not working for me (I'm using Hibernate 3.6).
criteria.add(Restrictions.eq(TABLECODEID, tableCodeID).ignoreCase());
I have also tried to use the ilike method but still doesn't work.
criteria.add(Restrictions.ilike(TABLECODEID, tableCodeID));
And this version too:
criteria.add(Restrictions.ilike(TABLECODEID, tableCodeID, MatchMode.ANYWHERE));
So now I'm getting this error when I try to create a query in Hibernate with HQL:
unexpected token: lower near line 1, column 81
My code looks like this:
StringBuffer queryString = new StringBuffer()
.append("from ListItem li ")
.append("where lower(li.tableCodeId) like :tableCodeId");
Query query = session.createQuery(queryString.toString());
query.setParameter("tableCodeId", tableCodeID.toLowerCase());
List<ListItem> listItemListAux = query.list();
What am I doing wrong?
You should resolve in this way, the MatchMode.ANYWHERE will do the trick:
criteria.add(Restrictions.ilike(TABLECODEID, tableCodeID, MatchMode.ANYWHERE));
At the end I used HQL and the problem was I was attacking the entity in the lower(li.tableCodeId) function, I had to use the DB column name lower(tablecodeid)

Calling postgreSQL stored procedure from Hibernate

When I try to call a stored procedure from Java - Hibernate. I got the below error.
org.hibernate.QueryException: Not all named parameters have been set:
and my Code
Query query = session.createSQLQuery("select commsrules.evalcommsrules(?::text,?::commsrules.t_commstype)");
query.setString(0, in_query);
query.setString(1, "TRIG");
result = query.list();
and I got the below exception
org.hibernate.QueryException: Not all named parameters have been set: [:text, :commsrules.t_commstype] [select commsrules.evalcommsrules(?::text,?::commsrules.t_commstype)]
at org.hibernate.internal.AbstractQueryImpl.verifyParameters(AbstractQueryImpl.java:390)
at org.hibernate.internal.SQLQueryImpl.verifyParameters(SQLQueryImpl.java:179)
at org.hibernate.internal.SQLQueryImpl.list(SQLQueryImpl.java:118)
please help me to resolve this issue
Looks like it's parsing :text and the other as a named parameter, even though you're trying to use positional parameters.
You could modify the query to use CAST instead of the :: shorthand.

Get dynamic SQL column names from Hibernate

I have an Oracle table that has a CLOB in it. Inside this CLOB can be a SQL statement. This can be changed at any time.
I am currently trying to dynamically run these SQL statements and return the column names and data back. This is to be used to dynamically create a table on the web page.
Using Hibernate, I create the query and get the data like so:
List<Object[]> queryResults = null;
SQLQuery q = session.createSQLQuery(sqlText);
queryResults = q.list();
This gets the data I need, but not the column names. I have tried using the getReturnAliases() method, but it throws an error that the "java.lang.UnsupportedOperationException: SQL queries do not currently support returning aliases"
So my question is: Is there a way through Hibernate to get these values dynamically?
You can use :
q.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
List<Map<String,Object>> aliasToValueMapList=query.list();
to get column names in createSQLQuery.
For more details please refer to this question.
You can use the addScalar method to define the columns.
Look at 16.1.1
https://docs.jboss.org/hibernate/orm/3.3/reference/en-US/html/querysql.html
You could implement a ResultTransformer ( http://docs.jboss.org/hibernate/orm/4.3/javadocs/org/hibernate/transform/ResultTransformer.html ) and set it on the native query. I think with a native SQL query you get the aliases as specified in the SQL as alias parameter in the callback method.
In 2018 I would suggest using NativeQueryTupleTransformer with native queries.
query.setResultTransformer(new NativeQueryTupleTransformer());
The result format is List<Tuple>. This format is very convenient to work with native SQL queries.

Hibernate query.list getting cast exception

I am trying to connect to sql server 2012. by hibernate.
sql query: SELECT top 3 P.,v. FROM TBLPOMASTER P join tblVendorMaster v on v.vendorid=p.VendorId where v.VendorCode=10001 and p.ApprovedStatus='Y'
I tried to translate HQL query as
List<TblPomaster> poMasterList = new ArrayList<TblPomaster>();
String sqlQuery = "from TblVendorMaster as v, TblPomaster as p where v.vendorId=p.vendorId and v.vendorCode=:vendorLoginId and p.approvedStatus='Y'";
Query query = HibernateUtil.getSession().createQuery(sqlQuery)
.setParameter("vendorLoginId", vendorLoginId);
query.setMaxResults(3);
poMasterList=query.list();
return poMasterList;
in the above code query is executing fine. But query.list() throwing RuntimeException as java.lang.String cannot be cast to java.lang.Long
What is the solution for the above error
You can change your attribute's type from String to Long
You can cast the value to long:
Long.valueOf(String s).longValue();
It is also recommended to get the results of your query with:
query.getResultList();
Looks like you are retrieving a value from your database and hibernate is trying to convert that to a Long value.
Perhaps you have mapped this table column to an erroneously typed attribute in your model class. I'd check which text values are defined a 'numeric' within your class.
--
#theMarceloR: vendorCode datatype is Long in model file. But I am sending vendorLoginId a string value. is this the problem?
Change the attribute in the model config from Long to String and see what happens.
SOLUTION:
Sagar updated his code and now he's sending vendorCode as a parameter, the value is casted from string to long.

Categories