I am using struts and hibernate in my problem. I tried the following query
String hql ="insert into "+
"OPENQUERY(OracleLinkedServer, \'SELECT * FROM report_access_log\') "+
"(CALLINGHOST, ACCESSTIMESTAMP, HTTPREQUESTMETHOD, ACCESSURL,"+
"HTTPRESPONSECODE, HTTPRESPONSETIMEMILLI, USERNAME, REPORTNAME, ID)"+
" values "+
"(:CALLINGHOST,:ACCESSTIMESTAMP,:HTTPREQUESTMETHOD,:ACCESSURL,:HTTPRESPONSECODE," +
":HTTPRESPONSETIMEMILLI,:USERNAME,:REPORTNAME,"+
"(select * from OPENQUERY(OracleLinkedServer,"+
"\'select SQ_RPT_ACC_LOG_ID.nextval from dual\')))";
Query query=session.createQuery(hql);
query.setString("CALLINGHOST", userLogReport.get(0).toString());
query.setDate("ACCESSTIMESTAMP", (Date)userLogReport.get(1));
query.setString("HTTPREQUESTMETHOD", userLogReport.get(2).toString());
query.setString("ACCESSURL", userLogReport.get(3).toString());
query.setString("HTTPRESPONSECODE", userLogReport.get(4).toString());
query.setInteger("HTTPRESPONSETIMEMILLI", (Integer)userLogReport.get(5));
query.setString("USERNAME", userLogReport.get(6).toString());
query.setString("REPORTNAME", userLogReport.get(7).toString());
The query printed on the console is as follows
insert into OPENQUERY(OracleLinkedServer, 'SELECT * FROM report_access_log')
(CALLINGHOST, ACCESSTIMESTAMP, HTTPREQUESTMETHOD, ACCESSURL,HTTPRESPONSECODE,
HTTPRESPONSETIMEMILLI, USERNAME, REPORTNAME, ID) values
(:CALLINGHOST,:ACCESSTIMESTAMP,:HTTPREQUESTMETHOD,:ACCESSURL,:HTTPRESPONSECODE:HTTPRESPONSE
TIMEMILLI,:USERNAME,:REPORTNAME,(select * from OPENQUERY(OracleLinkedServer,'select
SQ_RPT_ACC_LOG_ID.nextval from dual')))
i get a query syntax exception at column no 79 which is (CALLINGHOST,...
But when i ran the query in SQL it is getting executed. The query is as follows
insert into OPENQUERY(OracleLinkedServer, 'SELECT * FROM report_access_log')
(CALLINGHOST, ACCESSTIMESTAMP, HTTPREQUESTMETHOD, ACCESSURL,HTTPRESPONSECODE,
HTTPRESPONSETIMEMILLI, USERNAME, REPORTNAME, ID) values
('10.87.192.246','GET','/cci/bby/ImageViewer/viewImages.action','200',6,'su','Insert
Review',(select * from OPENQUERY(OracleLinkedServer,'select SQ_RPT_ACC_LOG_ID.nextval
from dual')))
Please explain the problem and provide me a solution for executing it from Java.
Thanks in advance.
HQL and SQL are two different languqges. HQL works on Hibernate entities, their properties, and associations between them. SQL works on database tables and columns.
Use
Query query = session.createSQLQuery(sql);
rather than
Query query = session.createQuery(hql);
Related
I'm trying to insert a row into DB2 but i can figure out how to get the generated ID.
With this code it's working but i can't get the ID:
String sql = "INSERT INTO MY_TABLE (MY_COLUMN) VALUES (?)";
Query query = entityManager.createNativeQuery(sql);
query.setParameter(1, "MY_VALUE");
query.executeUpdate();
I did some research, and tried to do like this:
String sql = "INSERT INTO MY_TABLE (MY_COLUMN) VALUES (?)";
Query query = entityManager.createNativeQuery(sql);
query.setParameter(1, "MY_VALUE");
BigDecimal id = (BigDecimal) query.getSingleResult();
But I got this error:
[org.hib.eng.jdb.spi.SqlExceptionHelper] (executor-thread-63) [jcc][t4][10103][10941][4.21.29] Method executeQuery cannot be used for update. ERRORCODE=-4476, SQLSTATE=null
javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not extract ResultSet
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1535)
at org.hibernate.query.internal.AbstractProducedQuery.getSingleResult(AbstractProducedQuery.java:1574)
...
What is the correct way to insert using NativeQuery and get the generated ID?
You can run comand like
-- You befor build str_sql in here
str_sql = 'INSERT INTO ............';
EXECUTE IMMEDIATE str_sql;
I have two tables in my database viz linkrecord(URL,NAME) and dishrate(dishname, rate,review). I want to create a 3rd table viz record which contains URL, dishname and rating from the 1st two table,in correspondance with dishname which is common to both table. I have tried the following Insert query but it shows the error: "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 '.NAME = dishrate.dishnameORDER BY dishrate.rate DESC' at line 1"
The query is:
String query= "INSERT INTO crawler.record (URL, Dishname, rate)"+
"SELECT linkrecord.URL, dishrate.dishname,dishrate.rate"+
"FROM linkrecord, dishrate"+
"WHERE linkrecord.NAME = dishrate.dishname"+
"ORDER BY dishrate.rate DESC";
Statement stmt=db.conn.createStatement();
stmt.executeUpdate(query);
I am unable to find the error in the above query.What should I do? Thank You
You forget the spaces and you ended up with query parts like:
INSERT INTO crawler.record (URL, Dishname,rate)<space missing here>SELECT
Correct way is:
String query= "INSERT INTO crawler.record (URL, Dishname, rate) "+
"SELECT linkrecord.URL, dishrate.dishname,dishrate.rate "+
"FROM linkrecord, dishrate "+
"WHERE linkrecord.NAME = dishrate.dishname "+
"ORDER BY dishrate.rate DESC";
I'm triggering a query using HQL, normally it should return empty resultset as it doesn't have any records w.r.t it. But, it throws
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:106)
My code is
String hql = "FROM com.pck.Person where userId = " + userId;
Query query = session.createQuery(hql);
#SuppressWarnings("unchecked")
List<Dashboard> listUserDetails = query.list(); <-- Problem here.
I'm expecting list size is 0 because there are no records w.r.t userId passed.
What changes do I need to do?
Lets say the value of userId was "abc12"
Given your code, the value of the string called hql would become:
"FROM com.pck.Person where userId = abc12"
If you took the value of that string and tried to run it as a query on any database, most of them would fail to understand that abc12 is a string. Normally it would be interpreted as a variable.
As other users mentioned including the single quotes would produce the desired query, but the recommended way to assign parameter values is this:
String hql = "FROM com.pck.Person where userId = :id"
query.setParameter("id", userId);
Looks like you are missing single quotes around userid.
Try with "FROM com.pck.Person where userId = '" + userId + "'";
or
Use named parameters with query.setParameter("userid", userId);
Posting the full stacktrace would help if this doesn't solve.
I am in the process of replacing jdbc with hibernate in my Web Application. I have learned that i don't have to write any SQL queries in this. Instead of this,criteria queries can help me.
These are my SQL queries which i want to convert to hibernate using criteria not HQL.
String getOrgIdQuery = "SELECT * FROM USER_DETAILS WHERE USER_ID= ?";
rsDeptName = stmt.executeQuery("SELECT DEPARTMENT_NAME FROM DEPARTMENT WHERE DEPARTMENT_ID ="+ DeptID + ";");
String insertCreateCdcValuesFirst = ("UPDATE User_Details SET User_Name=?, Organization_ID=?, Department_ID=?, Access_Ctrl = ?, User_Role=? WHERE User_ID = ?;");
First off all you must map your table with POJOS.
String getOrgIdQuery = "SELECT * FROM USER_DETAILS WHERE USER_ID= ?";
Preceding code in Hibernate look like following.
Criteria criteria = session.createCriteria(USER_DETAILS.class);
criteria.add(Restrictions.eq("user_id",yourUserId));
List<USER_DETAILS> list = criteria.list();
Your second select query is also same as preceding.
String insertCreateCdcValuesFirst = ("UPDATE User_Details SET User_Name=?, Organization_ID=?, Department_ID=?, Access_Ctrl = ?, User_Role=? WHERE User_ID = ?;");
With Hibernate Criteria update looks like following:
USER_DETAILS user_details = (USER_DETAILES) session.get(USER_DETAILS.class,yourUserId);
user_details.setUser_Name(NewUserName);
user_details.setOrganization_Id(newOrganizationId);
// some other fields update goes here
session.update(user_details);
tx.commit();
I hope this help you.
How to select last inserted 5 record from table using JPA with Hibernate?
public List<Sample> getAgencyChangeLastFiveRecords(){
return (ArrayList<Sample>) createQuery(
"select * from ( select * from sample order by id desc) where rownum<=5 order by rownum desc"
);
}
This is not working. What would be the corresponding HQL query?
may be you can try below
String hql="from Sample order by id desc"
Query.setMaxResults(5)