Cast exception in native sql query using hibernate - sql

I have a sql query using tables in it. the result set is return to a bean class which is not mapped to a table in database. the code is here:
SQLQuery q2=ss.createSQLQuery("select tbl_policy.policyNum as POLICYNUM FROM tbl_policy join tbl_product on tbl_policy.FK_productId = tbl_product.pk_product_id join tbl_code on tbl_policy.FK_codeId = tbl_code.PK_codeId join tbl_agriyear on tbl_policy.FK_agriYearId = tbl_agriyear.pk_agriyear_id where tbl_policy.FK_naturalInsurantId = :p1 and tbl_agriyear.AGRIYEAR =:p2");
q2.addScalar("POLICYNUM", Hibernate.STRING);
List<SearchPolicyBean> lsql = (List<SearchPolicyBean>)q2.list();
bean class name is: SearchPolicyBean
when I run it, in this line
System.out.println("Finalllll "+lsql.get(0).getPOLICYNUM());
this error appears:
java.lang.String cannot be cast to BO.SearchPolicyBean

addScalar(String columnAlias)
Is to Declare a scalar query result.
You declared it as a String here q2.addScalar("POLICYNUM", Hibernate.STRING);
So obviously the query results a String list not your SearchPolicyBean pojos .
If you are expectiong an list of your pojo classe you have to use
q2.addEntity(SearchPolicyBean.Class);
And change your query according.

for getting first element:
setPolicyNum((String) ((Object[])polList.get(i))[0]);

Related

Spring boot Postgres not return null when empty

I am using spring boot and spring data JPA with a Postgres database. There is a weird behaviour that happens when query something and the result is nothing.
In a lot of databases and projects when I make a query and the result was empty the returned object to java was null.
For example:
#Query(value = "select * from notification where WEBCODE = :webCode OR USERNAME = :username", nativeQuery = true)
Page<NotificationSQL> getNotificationsAsPage(#Param( "webCode" ) String webCode,#Param( "username" ) String username, Pageable pageable);
In this case I was suppose to get a null page. but in this case I am receiving an exception
org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:259)
...
Caused by: org.postgresql.util.PSQLException: ERROR: operator does not exist: character varying = bytea
Hint: No operator matches the given name and argument types. You might need to add explicit type casts.
Position: 42
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2552)
I do not understand why it does not just return a null object. It happens the same with the rest of the queries when empty rows and different objects as List classes. In a lot of projects this has not happen to me, the returned object when the query was right and empty rows was a null.
If the parameters are not null it works perfect, but the point is that these parameters sometimes are null and , as it can be seen in the image, the query works nice but with a result of empty rows.
Thanks in advance

Nhibernate and like statement on XML field

I have a wrapped fluent nhibernate framework that I'm reusing and have no control over the actual mapping.
In my entity object I have a property mapped as string to an XML column in sql.
Hence when I run a query like:
var myResult = (from myTable in DataManager.Session.Query<Table>()
where myTable.thatXmlFieldWhichIsMappedAsString.Contains(AnXmlSnippet))
select myTable).FirstOrDefault();
It is trying to use the LIKE operator in SQL which is invalid on that column type.
How can I get around this without having to select all the rows and converting to List first?
In case, that we do not need .Query() (LINQ), and we can use Criteria query or QueryOver, we can use conversion:
// the projection of the column with xml
// casted to nvarchar
var projection = Projections
.Cast(NHibernateUtil.StringClob
, Projections.Property("thatXmlFieldWhichIsMappedAsString"));
// criteria filtering with LIKE
var criteria = Restrictions.Like(projection, "searched xml");
// query and result
var query = session.QueryOver<MyEntity>()
.Where(criteria)
;
var result = query
.SingleOrDefault<MyEntity>()
;
From my experience this could lead to conversion into small nvarchar(255) - sql server... Then we can do it like this:
var projection = Projections
.SqlProjection("CAST(thatXmlFieldWhichIsMappedAsString as nvarchar(max)) AS str"
, new string[]{}
, new NHibernate.Type.IType[]{}
);

Error generated Hibernate Jpa Repository Query

I use this query with Jpa Repository:
#Query("select f.attrezzature from FoglioLavoro f where f.id = :idFoglioLavoro")
Page<AbstractAttrezzatura> findAttrezzaturaFoglioLavoro(#Param("idFoglioLavoro")Long idFoglioLavoro, Pageable pageable);
But when I use this query I obtain this error:
ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - 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 ') as col_0_0_ from foglio_lavoro fogliolavo0_, foglio_lavoro_attrezzature attrez' at line 1
And this is the generated spring-data query:
Hibernate:
select
count(.) as col_0_0_
from
foglio_lavoro fogliolavo0_,
foglio_lavoro_attrezzature attrezzatu1_,
abstract_attrezzatura abstractat2_
where
fogliolavo0_.id=attrezzatu1_.fogli_lavoro
and attrezzatu1_.attrezzature=abstractat2_.id
and fogliolavo0_.id=?
How can I solve it??
Thank you very much
When your repository method returns Page<T>, Spring Data JPA tries to infer a query for total count of elements from the query you specified, and sometimes the inferred query is wrong.
In such a case you need to specify a count query explicitly:
#Query(
value = "select f.attrezzature from FoglioLavoro f where f.id = :idFoglioLavoro",
countQuery = "select count(elements(f.attrezzature)) from FoglioLavoro f where f.id = :idFoglioLavoro")
Page<AbstractAttrezzatura> findAttrezzaturaFoglioLavoro(#Param("idFoglioLavoro")Long idFoglioLavoro, Pageable pageable);

multiple parameter "IN" prepared statement

I was trying to figure out how can I set multiple parameters for the IN clause in my SQL query using PreparedStatement.
For example in this SQL statement, I'll be having indefinite number of ?.
select * from ifs_db where img_hub = ? and country IN (multiple ?)
I've read about this in
PreparedStatement IN clause alternatives?
However I can't figure it out how to apply it to my SQL statement above.
There's not a standard way to handle this.
In SQL Server, you can use a table-valued parameter in a stored procedure and pass the countries in a table and use it in a join.
I've also seen cases where a comma-separated list is passed in and then parsed into a table by a function and then used in a join.
If your countries are standard ISO codes in a delimited list like '#US#UK#DE#NL#', you can use a rather simplistic construct like:
select * from ifs_db where img_hub = ? and ? LIKE '%#' + country + '#%'
Sormula will work for any data type (even custom types). This example uses int's for simplicity.
ArrayList<Integer> partNumbers = new ArrayList<Integer>();
partNumbers.add(999);
partNumbers.add(777);
partNumbers.add(1234);
// set up
Database database = new Database(getConnection());
Table<Inventory> inventoryTable = database.getTable(Inventory.class);
ArrayListSelectOperation<Inventory> operation =
new ArrayListSelectOperation<Inventory>(inventoryTable, "partNumberIn");
// show results
for (Inventory inventory: operation.selectAll(partNumbers))
System.out.println(inventory.getPartNumber());
You could use setArray method as mentioned in the javadoc below:
http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html#setArray(int, java.sql.Array)
Code:
PreparedStatement statement = connection.prepareStatement("Select * from test where field in (?)");
Array array = statement.getConnection().createArrayOf("VARCHAR", new Object[]{"AA1", "BB2","CC3"});
statement.setArray(1, array);
ResultSet rs = statement.executeQuery();

Spring Hibernate SQL Query

I have a VO class which has the getter and setter of another VO class too. For example:
Class DocumentVO{
PrintJobVO job;
PrintRunVO run;
String id;
getters and setters..
}
Now I have a requirement to use the Native SQL Query using spring hibernate. When I want to map the ids I have a problem. My query is,
select {r.*},{d.*}
from runs {r}, documents {d}
where {r}.RUN_ID as {r.id} = d.RUN_ID as {d.run.id}
Here run is of type PrintRunVO which has its id and other values. How can I map them in my SQL? I am getting an error like invalid user.table.column, table.column, or column specification.
What's the way to overcome this?
Use the Result Transformer concept in your plain SQL query.
String query = "myquery";
SQLQuery q = session.createSQLQuery(query);
q.addScalar("param1", Hibernate.STRING);
q.addScalar("param2", Hibernate.STRING);
q.setResultTransformer(Transformers.aliasToBean(MyVO.class));
q.setParameter("queryParam1", "some value");
return q.list();