How to Insert into DB2 with NativeQuery and get generated ID - java

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;

Related

How do I fix this problem - DERBY SQL Error: SCHEMA DOES NOT EXIST

I am trying to run this query, but I get the above SQL error.
query = "SELECT Count(*) as itemQuantity FROM ItemTable.Quantity WHERE ItemTable.BarCode = cast("+itemCode+" AS INTEGER)";
SQL Error java.sql.SQLSyntaxErrorException: Schema 'ITEMTABLE' does not exist
It seems "FROM ItemTable.Quantity" is wrong. just change it to "FROM ItemTable"
without using schema
query = "SELECT Count(Quantity) as itemQuantity FROM ItemTable WHERE BarCode = cast("+itemCode+" AS INTEGER)";
with schema
query = "SELECT Count(Quantity) as itemQuantity FROM dbo.ItemTable WHERE BarCode = cast("+itemCode+" AS INTEGER)";
in above dbo is database schema you can define your own if you like so

Using select inside insert query with preparedStatement

I want to write an insert query using preparedStatement. Inside it I want to put a selection query. I did the following but I get: You have an error in your SQL syntax
protected final String createStudentQuery = " INSERT INTO student (student_id, ed_level) VALUES (SELECT MAX(user_id) FROM user WHERE usertype ='Student' , ?)";
and then
stmt5 = conn.prepareStatement(createStudentQuery);
stmt5.setString(1, ed_level);
stmt5.executeUpdate();
All the declarations(connection, statement) have been made.
There are 2 values that needs to be inserted, student_id and ed_level . But in your select statement there is only one value, MAX(user_id). You have to also add the value for ed_level in the select query.
Also, your query should be:
INSERT INTO <TABLE_1> (COLUMN_1, COLUMN_2,...) SELECT COLUMN_1, COLUMN_2,... FROM <TABLE_2> WHERE <CONDITION>
I have modified the query to something like this:
INSERT INTO student (student_id, ed_level) VALUES ((SELECT MAX(user_id) FROM user WHERE usertype ='Student') , ?)
Hope this helps.

Using Select and where statement in Criteria

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.

PreparedStatement not executing correctly

query = "SELECT * FROM POST_COMMENT WHERE Post_date_time= ? AND Post_User= !;";
query = query.replace("?", "'"+post.getDatetime()+"'");
query = query.replace("!", Integer.toString(post.getPublisher().getID()));
PreparedStatement pstm = con.prepareStatement(query);
ResultSet rs = pstm.executeQuery();
The resulting query looks like this
SELECT * FROM POST_COMMENT WHERE Post_date_time= '2013-04-12 07:20:34.0' AND Post_User= 378;
Which works right in the MySQL prompt line but, when launched from prepared statement throws this error:
Exception in thread "main" 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 '07:20:34.0 AND Post_User=378' at line 1
But
pstm.setString(1, post.getDatetime());
pstm.setString(2, Integer.toString(post.getPublisher().getID()));
isn't working either.
Table definition
CREATE TABLE Post_Comment (
Comment_ID INTEGER(7) NOT NULL,
Post_date_time DATETIME NOT NULL,
Post_User INTEGER(7) NOT NULL,
PRIMARY KEY(Comment_ID, Post_date_time, Post_User),
CONSTRAINT Post_Comment_Post
FOREIGN KEY (Post_User, Post_date_time)
REFERENCES Post (User, date_time)
ON DELETE CASCADE
ON UPDATE CASCADE,
CONSTRAINT Post_Comment_Comment
FOREIGN KEY (Comment_ID)
REFERENCES Commentary (ID)
ON DELETE CASCADE
ON UPDATE CASCADE
)
;
Please help.
Take a look at the Java tutorials. You're not supposed to replace() the fields using the String functions.
You're supposed to call the "set" methods of the PreparedStatement.
EDIT:
No, take a look at the available methods. And what types the database columns expect. If you want a date, use setDate(), if you want an Integer, then use setInt(). Example:
query = "SELECT * FROM POST_COMMENT WHERE Post_date_time = ? AND Post_User = ?;";
PreparedStatement pstm = con.prepareStatement(query);
pstm.setDate(1, post.getDatetime());
pstm.setInt(2, post.getPublisher().getID());
ResultSet rs = pstm.executeQuery();
Also note that the query uses ? for both placeholders, not !.
query = "SELECT * FROM POST_COMMENT WHERE Post_date_time= ? AND Post_User= ?;";
PreparedStatement pstm = con.prepareStatement(query);
pstm.setObject(1, post.getDatetime());
pstm.setObject(2, post.getPublisher().getID());
ResultSet rs = pstm.executeQuery();

Open query in hibernate

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

Categories