JSON_VALUE usage in H2 database - java

In application code, we are using JSON_VALUE function for getting particular value from stored json.
SELECT * FROM EMPLOYEE WHERE JSON_VALUE(ADDR_JSON, '$.pinCode') != '390018'
When we are writing functional test cases which uses H2 database, it is resulting into following error:
nested exception is java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: JSON_VALUE in statement
Can you please suggest if anyone has some solution on this ?

H2 does not support accessing JSON attributes. See here for a list of supported functions: https://www.h2database.com/html/functions.html

Related

Geospatial Java update prepared statement for MySQL not working [duplicate]

I am using geotools library to extract the location information. With that I am getting an object of type
class com.vividsolutions.jts.geom.MultiPolygon
I now want to store this field in my mysql table with a jdbc connection .
When I directly try to insert it as
pstmtInsert.setObject(4, geoobject)
I am getting this error
Exception in thread "main" com.mysql.jdbc.MysqlDataTruncation: Data truncation: Cannot get geometry object from data you send to the GEOMETRY field
Answer
You need to convert the geometry object you have to well known text. You'll find information on how to do that in the vividsolutions API documentation.
geoobject.toText();
Insert / Update the data using the mysql GeomFromText method.
INSERT INTO geom VALUES (GeomFromText(#g));
It can be binary as well, e.g.
PreparedStatement preparedStatement = connection.prepareStatement
("INSERT INTO table (point, polygon) VALUES (PointFromWKB(?), GeomFromWKB(?))");
WKBWriter writer = new WKBWriter();
preparedStatement.setBytes(1, writer.write(point));
preparedStatement.setBytes(2, writer.write(polygon));
preparedStatement.executeUpdate();
MySql can't know how to store your GEO object, or what is his size. You should not store the object the way you're trying.
The PreparedStatement#setObject() documentation says :
The JDBC specification specifies a standard mapping from Java Object types to SQL types. The given argument will be converted to the corresponding SQL type before being sent to the database.
[...]
This method throws an exception if there is an ambiguity, for example, if the object is of a class implementing more than one of the interfaces named above.

HSQL database user lacks privilege or object not found error

I am trying to use hsqldb-2.3.4 to connect from Spring applicastion.
I created data base using the following details
Type : HSQL Database Engine Standalone
Driver: org.hsqldb.jdbcDriver
URL: jdbc:hsqldb:file:mydb
UserName: SA
Password: SA
I created a table named ALBUM under "MYDB" schema
In spring configuration file:
<bean id="jdbcTemplate"
class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dbcpDataSource" />
</bean>
<bean id="dbcpDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.hsqldb.jdbcDriver" />
<property name="url" value="jdbc:hsqldb:file:mydb" />
<property name="username" value="SA" />
<property name="password" value="SA" />
</bean>
And in my spring controller I am doing jdbcTemplate.query("SELECT * FROM MYDB.ALBUM", new AlbumRowMapper());
And It gives me exception:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT * FROM MYDB.ALBUM]; nested exception is java.sql.SQLSyntaxErrorException: user lacks privilege or object not found: ALBUM
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
If I execute same query through SQL editor of hsqldb it executes fine. Can you please help me with this.
As said by a previous response there is many possible causes. One of them is that the table isn't created because of syntax incompatibility. If specific DB vendor syntax or specific capability is used, HSQLDB will not recognize it. Then while the creation code is executed you could see that the table is not created for this syntax reason. For exemple if the entity is annoted with #Column(columnDefinition = "TEXT") the creation of the table will fail.
There is a work around which tell to HSQLDB to be in a compatible mode
for pgsl you should append your connection url with that
"spring.datasource.url=jdbc:hsqldb:mem:testdb;sql.syntax_pgs=true"
and for mysql with
"spring.datasource.url=jdbc:hsqldb:mem:testdb;sql.syntax_mys=true"
oracle
"spring.datasource.url=jdbc:hsqldb:mem:testdb;sql.syntax_ora=true"
note there is variant depending on your configuration
it could be hibernate.connection.url= or spring.datasource.url=
for those who don't use the hibernate schema creation but a SQL script you should use this kind of syntax in your script
SET DATABASE SQL SYNTAX ORA TRUE;
It will also fix issues due to vendor specific syntax in SQL request such as array_agg for posgresql
Nota bene : The the problem occurs very early when the code parse the model to create the schema and then is hidden in many lines of logs, then the unitTested code crash with a confusing and obscure exception "user lacks privilege or object not found error" which does not point the real problem at all. So make sure to read all the trace from the beginning and fix all possible issues
If you've tried all the other answers on this question, then it is most likely that you are facing a case-sensitivity issue.
HSQLDB is case-sensitive by default. If you don't specify the double quotes around the name of a schema or column or table, then it will by default convert that to uppercase. If your object has been created in uppercase, then you are in luck. If it is in lowercase, then you will have to surround your object name with double quotes.
For example:
CREATE MEMORY TABLE "t1"("product_id" INTEGER NOT NULL)
To select from this table you will have to use the following query
select "product_id" from "t1"
user lacks privilege or object not found can have multiple causes, the most obvious being you're accessing a table that does not exist. A less evident reason is that, when you run your code, the connection to a file database URL actually can create a DB. The scenario you're experiencing might be you've set up a DB using HSQL Database Manager, added tables and rows, but it's not this specific instance your Java code is using. You may want to check that you don't have multiple copies of these files: mydb.log, mydb.lck, mydb.properties, etc in your workspace. In the case your Java code did create those files, the location depends on how you run your program. In a Maven project run inside Netbeans for example, the files are stored alongside the pom.xml.
I had the error user lacks privilege or object not found while trying to create a table in an empty in-memory database.
I used spring.datasource.schema and the problem was that I missed a semicolon in my SQL file after the "CREATE TABLE"-Statement (which was followed by "CREATE INDEX").
I had similar issue with the error 'org.hsqldb.HsqlException: user lacks privilege or object not found: DAYS_BETWEEN' turned out DAYS_BETWEEN is not recognized by hsqldb as a function. use DATEDIFF instead.
DATEDIFF ( <datetime value expr 1>, <datetime value expr 2> )
When running a HSWLDB server. for example your java config file has:
hsql.jdbc.url = jdbc:hsqldb:hsql://localhost:9005/YOURDB;sql.enforce_strict_size=true;hsqldb.tx=mvcc
check to make sure that your set a server.dbname.#. for example my server.properties file:
server.database.0=eventsdb
server.dbname.0=eventsdb
server.port=9005
I was inserting the data in hsql db using following script
INSERT INTO Greeting (text) VALUES ("Hello World");
I was getting issue related to the Hello World object not found and HSQL database user lacks privilege or object not found error
which I changed into the below script
INSERT INTO Greeting (text) VALUES ('Hello World');
And now it is working fine.
Add these two extra properties:
spring.jpa.hibernate.naming.implicit-strategy=
org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=
org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
I bumped into kind of the same problem recently. We are running a grails application and someone inserted a SQL script into the BootStrap file (that's the entry point for grails). That script was supposed to be run only in the production environment, however because of bad logic it was running in test as well. So the error I got was:
User lacks privilege or object not found:
without any more clarification...
I just had to make sure the script was not run in the test environment and it fixed the problem for me, though it took me 3 hours to figure it out. I know it is very, very specific issue but still if I can save someone a couple of hours of code digging that would be great.
I was having the same mistake. In my case I was forgetting to put the apas in the strings.
I was doing String test = "inputTest";
The correct one is String test = "'inputTest'";
The error was occurring when I was trying to put something in the database
connection.createStatement.execute("INSERT INTO tableTest values(" + test +")";
In my case, just put the quotation marks ' to correct the error.
In my case the error occured because i did NOT put the TABLE_NAME into double quotes "TABLE_NAME" and had the oracle schema prefix.
Not working:
SELECT * FROM FOOSCHEMA.BAR_TABLE
Working:
SELECT * FROM "BAR_TABLE"
had this issue with concatenating variables in insert statement. this worked
// var1, var3, var4 are String variables
// var2 and var5 are Integer variables
result = statement.executeUpdate("INSERT INTO newTable VALUES ('"+var1+"',"+var2+",'"+var3+"','"+var4+"',"+var5 +")");
In my case the issue was caused by the absence (I'd commented it out by mistake) of the following line in persistence.xml:
<property name="hibernate.hbm2ddl.auto" value="update"/>
which prevented Hibernate from emitting the DDL to create the required schema elements...
(different Hibernate wrappers will have different mechanisms to specify properties; I'm using JPA here)
I had this error while trying to run my application without specifying the "Path" field in Intellij IDEA data source (database) properties. Everything else was configured correctly.
I was able to run scripts in IDEA database console and they executed correctly, but without giving a path to the IDEA, it was unable to identify where to connect, which caused errors.
You have to run the Database in server mode and connect.Otherwise it wont connect from external application and give error similar to user lacks privilege.
Also change the url of database in spring configuration file accordingly when running DB in server mode.
Sample command to run DB in server mode
$java -cp lib/hsqldb.jar org.hsqldb.server.Server --database.0 file:data/mydb --dbname.0 Test
Format of URL in configuration file
jdbc:hsqldb:hsql://localhost/Test
In my case, one of the columns had the name 'key' with the missing #Column(name = "key") annotation so that in the logs you could see the query that created the table but in fact it was not there. So be careful with column names
For what it's worth - I had this same problem. I had a column named 'TYPE', which I renamed to 'XTYPE' and a column named ORDER which I renamed to 'XORDER' and the problem went away.
Yet another reason could be a misspelt field name. If your actual table has an id column named albumid and you'd used album_id, then too this could occur.
As another anwer remarked, case differences in field names too need to be taken care of.
I faced the same issue and found there was more than one PersistenceUnit (ReadOnly and ReadWrite) , So the tables in HSQLDDB created using a schema from one persistence unit resulted in exception(HSQL database user lacks privilege or object not found error) being thrown when accessed from other persistence unit .It happens when tables are created from one session in JPA and accessed from another session
In my case the table MY_TABLE was in the schema SOME_SCHEMA. So calling select/insert etc. directly didn't work. To fix:
add file schema.sql to the resources folder
in this file add the line CREATE SCHEMA YOUR_SCHEMA_NAME;

Issue in DB2 or Java - Handling CLOB data type

I need to pull comma-separated values from DB2 exactly as in this question, so after quick googling I found the solution by using following functions in my select clause:
SUBSTR(XMLCAST(XMLGROUP(', ' || col_1 AS C ORDER BY col_1) AS clob), 3) AS RES_COL
Now, the output returned is CLOB and not VARCHAR. I tried by increasing VARCHAR limit, but it was giving CAST error. Now, I am getting following exception while reading this CLOB column in JAVA.
SQL state [HY000]; error code [0]; [BEA][DB2 JDBC Driver]SQLDIAGGRP was specified and not null.; nested exception is java.sql.SQLException: [BEA][DB2 JDBC Driver]SQLDIAGGRP was specified and not null.
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:83)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:407)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:458)
I am not able to find any help regarding what this exception means exactly? What I understand is it is related to JDBC Driver, but can someone explain more on this?
Otherwise, Can DB2 experts tell me how to return VARCHAR instead of CLOB, so that JAVA does not complain when queried?
I was able to resolve this issue by using CAST and TRIM DB2 functions over XMLCAST output. Now I am able to return VARCHAR from the query and JAVA code is working fine too.
SUBSTR(TRIM(CAST(XMLCAST(XMLGROUP(', ' || col_1 AS C ORDER BY col_1) AS clob) AS VARCHAR(4096))), 3) AS RES_COL

insert geospatial datatype( mutipolygon) in mysql with java( jdbc)

I am using geotools library to extract the location information. With that I am getting an object of type
class com.vividsolutions.jts.geom.MultiPolygon
I now want to store this field in my mysql table with a jdbc connection .
When I directly try to insert it as
pstmtInsert.setObject(4, geoobject)
I am getting this error
Exception in thread "main" com.mysql.jdbc.MysqlDataTruncation: Data truncation: Cannot get geometry object from data you send to the GEOMETRY field
Answer
You need to convert the geometry object you have to well known text. You'll find information on how to do that in the vividsolutions API documentation.
geoobject.toText();
Insert / Update the data using the mysql GeomFromText method.
INSERT INTO geom VALUES (GeomFromText(#g));
It can be binary as well, e.g.
PreparedStatement preparedStatement = connection.prepareStatement
("INSERT INTO table (point, polygon) VALUES (PointFromWKB(?), GeomFromWKB(?))");
WKBWriter writer = new WKBWriter();
preparedStatement.setBytes(1, writer.write(point));
preparedStatement.setBytes(2, writer.write(polygon));
preparedStatement.executeUpdate();
MySql can't know how to store your GEO object, or what is his size. You should not store the object the way you're trying.
The PreparedStatement#setObject() documentation says :
The JDBC specification specifies a standard mapping from Java Object types to SQL types. The given argument will be converted to the corresponding SQL type before being sent to the database.
[...]
This method throws an exception if there is an ambiguity, for example, if the object is of a class implementing more than one of the interfaces named above.

oracle collection as function return type

We have a database function to cache sequence values. It accepts a sequence object name and a fetch size, increments the sequence and return the values.
The return type is a oracle collection.
Here is the definition of the db types used by the function:
create or replace type icn_num_type as object(v_inc_num number);
create or replace type icn_num_type_table as table of icn_num_type; --this is returned
The values returned by the function are cached on the application side. We are using ibatis for DAO. All this worked well when the function, types and the sequence objects were all in the same schema.
Now we have the function, types and sequences defined in one parent schema. The user schema has synonyms to the all the above mentioned objects. I am facing the following error now:
--- The error occurred while executing query procedure.
--- Check the {? = call seq_inc(?, ?)}.
--- Check the output parameters (register output parameters failed).
--- Cause: java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist
ORA-06512: at "SYS.DBMS_PICKLER", line 18
ORA-06512: at "SYS.DBMS_PICKLER", line 58
ORA-06512: at line 1
However when we access the function from SQLDeveloper(user schema) it works fine.
Could some one help me on this issue?
Seems there were issues (restrictions / bugs) with synonyms and Object types back in 9iR2 for java. Google for ORA-21700 and DBMS_PICKLER
I suspect you've got some issue with the JDBC driver being used for iBatis that is resolved for the JDBC version used for SQL Developer.
Grab something like SQuirrel SQL Client and try the JDBC driver you are using for iBatis with that to see if you can reproduce.

Categories

Resources