Update query in createNativeQuery - java

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();

Related

JPA method not returning results even though the generated query returns results when used in postgres console

I'm not getting any results for JPA method even though when i log the query and try it on the database console i get the correct results
REPO:
public interface FireWeatherDay1CatRiskRepository extends
JpaRepository<FireWeatherDay1CatRisk, Long> {
List<FireWeatherDay1CatRisk> findByAdvTs(Instant advTs);
}
GENERATED QUERY:
select fireweathe0_.id as id1_0_,
fireweathe0_.adv_ts as adv_ts2_0_,
fireweathe0_.category as category3_0_,
fireweathe0_."end" as end4_0_,
fireweathe0_.geom as geom5_0_,
fireweathe0_.start as start6_0_
from fire_weather_day1_cat_risk fireweathe0_
where fireweathe0_.adv_ts='2021-09-28T17:00:00Z';
Again, no results return when using the JPA method, but the query generated seems to be correct when i manually run the query in my postgres console it works fine.
You are not executing the same query.
What JPA is executing is most certainly
select fireweathe0_.id as id1_0_,
fireweathe0_.adv_ts as adv_ts2_0_,
fireweathe0_.category as category3_0_,
fireweathe0_."end" as end4_0_,
fireweathe0_.geom as geom5_0_,
fireweathe0_.start as start6_0_
from fire_weather_day1_cat_risk fireweathe0_
where fireweathe0_.adv_ts=?;
plus a value for the bind value.
The problem is most likely that some conversion happens to the instant, probably involving the current timezone of your JVM or of the database.

Get results as CSV from postgresql using hibernate

I execute a query which should return the results as a CSV to the STDOUT.
When I execute my query in the pgAdmin I successfully get results.
However when I execute the same query using hibernate I gets the following exception:
javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not extract ResultSet
I mustn't show the tables structure but I know that the sql is fine(I've copied the entire content of "sql" then I execute it in pgAdmin); The query looks like:
String sql = "COPY (" + sqlQuery + ") TO STDOUT WITH CSV";
Then I execute it as the following:
Query query = getEntityManager().createNativeQuery(sql);
Object result = query.getSingleResult(); // I also tried the other get results method...(`getFirstresult()` has returned 0)
In any related questions I have found, I saw that the OP put the csv into a file instead of stdout.
Is it possible to return csv result using hibernate?
Thanks in advance!
AFAIK, COPY is not supported natively by PostgreSQL JDBC driver (last tested on postgresql-9.4.1208.jre7). Thus, Hibernate can not run the command.
If you really need to use COPY you should consider a CopyManager: how to copy a data from file to PostgreSQL using JDBC?
But personally, I would advocate you change your approach. Loading data with COPY looks like a kind of a hack to me.
You can have this done with univocity-parsers using two lines of code. You just need to get a resultset from your query and do this:
CsvRoutines routines = new CsvRoutines();
routines.write(resultset, new File("/path/to/output.csv"), "UTF-8");
The write() method takes care of everything. The resultset is closed by the routine automatically.

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

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)

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