I'm trying to execute an insert operation to an Oracle DB Table from Java with JPA.
The following is my code:
String coCode;
String coDescription;
/* some operations on data ... */
String queryStatement =
"insert into MANAGER_DATA (CO_CODE, CO_DESCRIPTION) values (?1, ?2)";
Query updateQuery = getEntityManager(context).createNativeQuery(queryStatement);
updateQuery.setParameter(1, coCode);
updateQuery.setParameter(2, coDescription.compareTo("") == 0 ? null : coDescription);
updateQuery.executeUpdate();
The problem is that coDescription can be null in case of an empty String and, in that case, I want the null value to be added in the table as well (coCode is primary key but coDescription is nullable). Apparently I cannot pass a null value to the setParameter function directly, as I am doing above.
How can I solve this and allow the null value to be added to my DB table?
Looks like you might be using old Hibernate version affected by HHH-9165 createNativeQuery's setParameter does not support null bug. Upgrade to Hibernate 5.0.2 or newer to resolve it. As per mentioned Jira:
Just tested it with Hibernate 5.0.2 and the bug seems to be resolved.
Oracle evaluates empty strings as null.
For example:
insert into MANAGER_DATA (CO_CODE, CO_DESCRIPTION) values ('my_code', '')
will insert this row: ('my_code', null).
Therefore you can leave it empty string.
Related
I have an oracle database, and am trying to delete a record based on the client number, with the query returning the rowid of the deleted record. When executing the query, I am getting the following exception: java.lang.IllegalArgumentException: Field (rowid) is not contained in Row. If I attempt returning a different field (such as the client_number field itself) instead of rowid, the query works perfectly.
The query I am trying to execute looks like this:
ClientDetails clt = CLIENT_DETAILS.as("clt");
ClientDetailsRecord result = context.deleteFrom(clt)
.where(clt.CLIENT_NUMBER.equal(clientNumber))
.returning(rowid())
.fetchOne();
Is this a limitation of Jooq, or am I doing this the wrong way?
This is a known (and unfortunate) limitation of jOOQ 3.x, which can only return declared columns of your table CLIENT_DETAILS, no "system" columns like ROWID or any expressions for that matter. The relevant feature request to rectify this is: https://github.com/jOOQ/jOOQ/issues/5622
You could work around this limitation by creating your own CLIENT_DETAILS table which includes a "synthetic" ROWID column, e.g. by:
Extending the CustomTable type
Extending the code generator by adding the ROWID column to your CLIENT_DETAILS table (beware that this can have undesired side-effects, e.g. when calling UpdatableRecord.store())
I want to insert the default value from database when my field is null. I use an Oracle Database.
CREATE TABLE "EMPLOYEE"
("COL1" VARCHAR2(800) NOT NULL ENABLE,
"COL2" VARCHAR2(100) DEFAULT NOT NULL 'toto',
CONSTRAINT "PK_EMPLOYEE" PRIMARY KEY ("COL1")
with a simple SQL request, we can write:
insert into EMPLOYEE(COL1,COL2) values ('titi', default)
How can i do this with annotations MyBatis in Spring? I must create an HandlerType?
In mapper XML, build dynamically the SQL (add the col2 column and value when not null):
insert into employee (col1<if test="col2 != null">, col2</if>)
values (#{COL1}<if test="col2 != null">, #{col2}</if>)
EDIT: since value in annotation must be constant, I used to think dynamic SQl was not possible in annotation, but there is a trick I have found here: How to use dynamic SQL query in MyBatis with annotation(how to use selectProvider)? and checked it myself.
To use dynamic SQL this into an annotation, surround it with "script" tags:
#Insert("<script>insert into employee (col1<if test='col2 != null'>, col2</if>)
values (#{COL1}<if test='col2 != null'>, #{col2}</if>)</script>")
In tests, just escape double quotes " or replace them with simple quotes '
It should work if you omit the COL2 in your colum definition of the insert statement. Because the DB recognizes, that there is no value for the new row and it will apply the default value from the create table statement.
Have you tried something like this?
public interface EmployeeDAO {
String INSERT = "insert into employee (col1) values (#{COL1})";
#Insert(INSERT)
public int insertDefault(PersonDO p) throws Exception;
}
so i have a HQL code in Java that does
ClassA myAObj = null;
myAObj = (ClassA) hs.get(ClassA.class, classId)
this line executes without issue many times. however, there are cases for a few primary key ID where HQL return a null value and myAObj is null. This is considered odd because i took the console's SQL equivalent scriptand ran it in SQL developer and i did not get a null result.
What is the possible cause of this?
The classId you are passing to hs.get(ClassA.class, classId) is not present(not matching) in your table records.
Better you debug code or print classId value then verify that record exist in your table.
I want to insert null data to Teradata with JDBC connection on JAVA.
First of all I try this:
PreparedStatement stmt;
String qm="Insert into db.user values (?,?,?,?,?,?,?)";
connection= DriverManager.getConnection
(
"jdbc:teradata://192.xxx.x.xx/database=DBC,tmode=ANSI,charset=UTF8","user","passw0rd" );
stmt = connection.prepareStatement(qm);
//some code here to open while loop
stmt.setObject(i,null); // This isnt working with Terada JDBC. It is working for Oracle and MSSQL JDBC
//and I finish my code
And after, that I tried this instead of stmt.setObject(i,null); :
stmt.setNull(i,rsmd.getColumnType(i),rsmd.getColumnTypeName(i));
rsmd.getColumnType(i) is equal to 97
rsmd.getColumnTypeName(i) is equal to DATE
Yes it is true my field is DATE.
But it gives this ERROR:
ERROR : [Teradata JDBC Driver] [TeraJDBC 14.10.00.17] [Error 857] [SQLState HY000] Two different data types are being set for parameter 17 (449 & 749)
How can I fix this.
I used in the past the setNull(i, Types.#field type#) in a custom DB layer for TD.
However if you search the codes returned in the exception you'll find that they represent a Date and a Varchar, as if, at the same position, you sometimes pass a Date type and sometimes a Varchar.
Are you by chance passing not null dates as Date-like strings (e.g. "2015-08-18"), and not as java.sql.Date objects?
If that's the case you should change the code to use java.sql.Date objects and this will solve your issue.
Typically if you wish to INSERT a NULL value into ColC I would suggest using the following method with your INSERT ... VALUES statement:
INSERT (ColA, ColB, ColD, ColE) VALUES (1000, 'Testing Null', 1.00, DATE '2013-06-30);
Teradata will take the absence of the column in the INSERT statement to place either the pre-defined DEFAULT value or NULL for the column.
What if you try the following:
stmt.SetNull(i,Types.NULL)
The workaround for this issue is to cast the NULL to be a VARCHAR, so that it is compatible.
INSERT INTO XYA(PKEY,REF_KEY) VALUES(2,cast(null as varchar(10)));
This command on SQL Server
UPDATE tbl SET name='Hi' WHERE id=''
works if 'id' is set as an integer value, but it does not work on H2.
What may be the solution?
If ID is integer, you shouldn't use quotes for the value:
UPDATE TEST SET NAME='Hi' WHERE ID = 5; // not ID = '5'
Many databases will accept the quoted version, but are not required to by the SQL language specification.
UPDATE TEST SET NAME='Hi' WHERE ID='1';
that is working in sql server even if id field is integer
but if you want to update the row where id is null then you have to use below statement :
UPDATE TEST SET NAME='Hi' WHERE ID is Null;
instead of UPDATE TEST SET NAME='Hi' WHERE ID ='';
And if id is varchar then you can use your statement to update the values where ID is not null and data is not available there.
But if you want to update the values for record where NULL value of ID field then you have to use
UPDATE TEST SET NAME='Hi' WHERE ID is Null;
H2 throws an exception because it can't convert the empty string '' to a number. H2 internally uses java.lang.Long.parseLong("") which fails with java.lang.NumberFormatException: For input string: "".
For the SQL script:
drop table tbl;
create table tbl(id int primary key, name varchar(255));
insert into tbl values(1, 'Hello');
UPDATE tbl SET name='Hi' WHERE id='';
H2 will throw the exception:
Data conversion error converting [22018-161]
Most other databases (PostgreSQL, Apache Derby, HSQLDB) throw a similar exception.
You need to use a number, or IS NULL as in:
UPDATE tbl SET name='Hi' WHERE id IS NULL;
or
UPDATE tbl SET name='Hi' WHERE id = 0;