Hibernate createSQLQuery() - list() and executeUpdate() - delete and select statement - java

We are using the following SQL Statement and execute via createSQLQuery() - list() instead of executeUpdate()
a) delete from employee where nbr in ('1', '2', '3')
b) delete from emp_details where empNbr=(select nbr from employee where name = 'Somu')
Both the queries works fine in SQL Client but throws the following exception
org.hibernate.exception.SQLStateConverter.handledNonSpecificException
(SQLStateConverter.java:126), org.hibernate.exception.SQLStateConverter.
convert(SQLStateConverter.java:114),org.hibernate.exception.
JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66),
org.hibernate.loader.Loader.doList(Loader.java:2235),
org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129),
org.hibernate.loader.Loader.list(Loader.java:2124),
org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:312),
org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1723),
org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:165),
org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:175)
There is no issue with the query as the query works fine in SQL client.
Question:
1) Can we pass or execute deletion script via createSQLQuery() - list() or not?
2) Is it wrong to use createSQLQuery() - list() for deletion script?

you have to call executeUpdate() instead of list on the query you get back from createSQLQuery() if you want to execute a delete statement !

It is a wrong practice to use .list() for any update or delete script.
As mentioned above by Andre, you need to use .executeUpdate which has a return type of int, returning the number of rows affected by the executeUpdate command.
SQLQuery sqlQuery = session.createSQLQuery("delete from employee where nbr in (1,2,3)");
sqlQuery.executeUpdate();
Also its a good practice to use named parameters for passing your parameters in the query. (Read this for reference)

Related

How to retrieve output param from Stored Procedure with Hibernate

I am trying to execute a Stored Procedure which updates a column and retrieves the filename from the same table after updating
StoredProcedure:
CREATE DEFINER=`test`#`%` PROCEDURE `update_count`(
IN in_testID VARCHAR(64),
OUT out_FileName VARCHAR(100),
OUT out_Message VARCHAR(100))
BEGIN
UPDATE files SET count=count+1 WHERE testID=in_testID;
SELECT FileName INTO out_FileName FROM files WHERE testID = in_testID;
SET out_Message = 'File updated uccessfully';
END
JavaCode to execute this StoredProcedure:
Query query = session.createSQLQuery("CALL update_count(:in_testID, #out_FileName, #out_Message)").addEntity(FilesBean.class)
.setParameter("in_testID",body.getTestId());
query.executeUpdate();
Updated the query.executeUpdate() with query.list(). But the line returning a error ResultSet is from UPDATE. No Data
I need to fix this with using the createSQLQuery
The easiest way to do that is return the out parameter as part of the returning parameters (relevant only if you have access to the store procedures).
just add a store procedure like the following one
create procedure myProcedure_only_in_prams (
in in_Id int)
begin
call myProcedure(in_id,#out_Id) ;
select #out_id
END;
after done that it quite simple to use it with Hibernate in the following way
Query query = session.createSQLQuery(
"CALL myProcedure_only_in_parms (:in_Id)")
.setParameter("in_id", 123);
List result = query.list();
The result contains the out parameter, if you want return multiply parameters you can add it by doing select #parm1,#parm2,... ,#parmn
Hope it helped

Update query in createNativeQuery

I want to run an Update query using createNativeQuery in entityManager. I am not able to run it.
My class structure :
class ABC_DAO
{
List<a> = entityManager.createNativeQuery(select.......); //sql1 : it is working fine
Sysout("some value"); // it is working
entityManager.createNativeQuery(update.......);// ***sql2 :it is not working***
Sysout("some value"); // it is working
}
Hibernate is not executing sql2 but executing sql2. We are using Postgres db. This query has to be in Sql. We are using Hibernate with JPA.
Let my try to help you on behalf of your erroneous code example and problem description.
1) You will only get a List as result of a query if you call getResultList() on it, otherwise sql1 would not work (Please post the complete code, if you want to get help):
List<a> = entityManager.createNativeQuery("sql1", a.class).getResultList();
2) For update statements you have to call the method executeUpdate() and not getResultList() (or getSingleResult())to send the native SQL statement to the database:
int countUpdated = entityManager.createNativeQuery("sql2").executeUpdate();

Criteria Query returnig all records

SQL :
String hql1 = "SELECT /* PARALLEL(MVR,16) PARALLEL(MVRS,16)*/ * FROM
ICM MINUS SELECT I1.* FROM ICM I1 , C1_ICM_STATIC I2 WHERE
I1.METRIC_DIRECTION=I2.METRIC_DIRECTION AND
I1.METRIC_NAME=I2.METRIC_NAME AND I1.METRIC_UNIT=I2.METRIC_UNIT AND
I1.TERMINATION_POINT_ID=I2.TERMINATION_POINT_ID AND
I1.TERMINATION_POINT_NAME=I2.TERMINATION_POINT_NAME AND
I1.TERMINATION_POINT_TYPE=I2.TERMINATION_POINT_TYPE";
Criteria Query
icms1 = (List<ICM>) session.createCriteria(ICM.class, hql1).list();
I have executed hql1 using SQL Developer then I got only one result, but when I have integrated SQL Query with Criteria it returning me all records in ICM table.
If SQL query returning only one result in SQL Developer, Why criteria API returning all records in ICM table?
Why criteria API returning all records in ICM table?
Technically you are not using criteria api for associations.
Try something like this.
Refer.
return criteria.createCriteria(A.class)
.createCriteria("b", "join_between_a_b")
.createCriteria("c", "join_between_b_c")
.createCriteria("d", "join_between_c_d")
.add(Restrictions.eq("some_field_of_D", someValue));
You should learn to read API documentation.
The second Session.createCriteria() argument is the alias that you want to assign to the root entity. It's not a HQL query. HQL queries are not executed using Session.createCriteria(). They're executed using Session.createQuery().
BTW, your query is not a HQL query at all. It's a SQL query. SQL and HQL are 2 different languages. To execute a SQL query, you need createSQLQuery().

How to get ResultSet from executeBatch?

I need to get the result set from an executed batch :
String [] queries = {"create volatile table testTable as (select * from orders) with data;",
"select top 10 * from testTable;" ,
"drop table testTable" };
for (String query : queries) {
statement.addBatch(query);
}
statement.executeBatch();
Ones i execute batch how can i get the result set from the select query ?
In short, you should not. Plain multiple execute() should be used.
As as according to the javadoc of executeBatch(), it should not support getResultSet()/getMoreResults() API.
Also, in JDBC™ 4.0 Specification #14.1.2
Only DDL and DML commands that return a simple update count may be
executed as part of a batch. The method executeBatch throws a
BatchUpdateException if any of the commands in the batch fail to
execute properly or if a command attempts to return a result set.
But some JDBC drivers might do support, try at your own risk.
I can think of 2 options from the top of my head.
1) As the other guy said...
"Plain multiple execute() should be used"
this way you can get the result set.
2) you can query after you execute your batch and get its info from the db.
According to the Java 7 API, the 'executeBatch" function doesn't return an object of ResultSet, but an array of integers. You can process the values based on the API to see which commands in the batch were successful.

how to execute the stored procedure in hibernate 3

I am new in hibernate. I am using hibernate 3 in my application using hibernate annotations , I am developing application in struts 1.3.
My question is :
I have googled a lot but could not understand how to call a stored procedure in hibernate using annotations , I have a simple scenario : suppose I have 2 fields in my jsp say 1) code 2) name , I have created a stored procedure in database for inserting those records into table. Now my problem is that how to execute it
List<MyBean> list = sessionFactory.getCurrentSession()
.getNamedQuery("mySp")
.setParameter("code", code)
.setParameter("name", name)
I don't know the exact code how to do this. But I guess something like that actually I come from jdbc background therefore have no idea how to do this and same thing I want when selecting the data from database using stored procedure.
Hibernate provides many simple ways to call a SP like
Native SQL
Named Query in native SQL as Annotation/XML mapping file
Following link shows how each of above can be implemented
http://www.mkyong.com/hibernate/how-to-call-store-procedure-in-hibernate/
http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html#sp_query
Sample to run native SQL query using hibernate:
Session session = getSession();
SQLQuery sqlQuery = session.createSQLQuery("SELECT COUNT(id) FROM tableName WHERE external_id = :external_id");
sqlQuery.setParameter("external_id", idValue);
int count = ((BigInteger) sqlQuery.uniqueResult()).intValue();
releaseSession(session);
You can execute your stored procedure using Hibernate's SQLQuery with the same SQL as when you call it against the database. For example, in postgreSQL:
String query = "select schema.procedure_name(:param1)";
SQLQuery sqlquery = sessionFactory.getCurrentSession().createSQLQuery(query);
sqlquery.setInteger("param1", "this is first parameter");
sqlQuery.list();
Hope it helps.

Categories

Resources