Entity Class
#Id
#Column(length=3)
private String BankID;
DAO Class
String sSQL = "SELECT x FROM Bank x WHERE x.BankID =?1 ";
Query aQuery = m_aEntityManager.createQuery(sSQL);
aQuery.setParameter(1, sBankID);
If I pass '001' to sBankID, everything is OK.
But if I pass '0001' to sBankID, OpenJPA just throw PersistenceException: DB2 SQL error: SQLCODE: -302, SQLSTATE: 22001, SQLERRMC: null
Is there anyway just to set OpenJPA turn off column lenth validation?(if I don't want modify any eneity and dao source codes)
DB2 9, OpenJPA 1.2
Thanks a lot!
Is there anyway just to set OpenJPA turn off column lenth
validation?(if I don't want modify any eneity and dao source codes)...
DB2 SQL error: SQLCODE: -302, SQLSTATE: 22001, SQLERRMC: null
This exception is coming from DB2 and OpenJPA is merely exposing the problem as a PersistenceException. You will need to pass in proper length data to get the exception to go away... or modify your table definition.
Related
My following native query is not working:
Query createNativeQuery = entityManager.createNativeQuery(
"select id from cscache where id=? for update ");
Environment Details:
Mysql 5.6
Jboss 5.1
JPA 1.0
Error:
2014-12-12 10:20:14,581 WARN [org.hibernate.util.JDBCExceptionReporter]
SQL Error: 1064, SQLState: 42000 (http-0.0.0.0-8543-3:)
2014-12-12 10:20:14,581 ERROR [org.hibernate.util.JDBCExceptionReporter]
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 'limit 2' at line 1 (http-0.0.0.0-8543-3:)
For Update basically puts a lock on rows, to achieve the same using JPA you need to use Lock Modes. To set the lock, you can use EntityManager or TypeQuery and use LockModeType.PESSIMISTIC_WRITE.
Refer this article
I haven't actually done a for update in hibernate, but I believe you can (and should?) do it on the Session or query object. Why not let hibernate do it instead of executing a native query?
According to the documentation on locking (Chapter 5: Locking, you can set the lock mode on either the session or the query.
Cscache cscache = (Cscache )session.get( Cscache.class, id, LockOptions.UPGRADE );
Specifying the LockOptions should result in a SELECT ... FOR UPDATE being executed.
Not familiar with JPA specifically, but it appears you're not telling it what the value of ? is. Check out setParameter.
I'm having trouble when trying to run the following query against an in memory H2 (version 1.4.181) table:
Object result = hibernateSession
.createSQLQuery("show columns from :myTable")
.setString("myTable", "some_table")
.list();
This query causes the following exception:
Caused by: org.h2.jdbc.JdbcSQLException: Syntax error in SQL statement "SHOW COLUMNS FROM ?[*] "; expected "identifier"; SQL statement: show columns from ? [42001-181]
...
...
...
I had done some debbuging and I found that during parse of query, the character "?" is tested to check if it is a valid identififer and it fails, causing the rise of exception (class org.h2.command.Parser, line 3027):
//currentToken is "?" at this point
if (currentTokenType != IDENTIFIER) {
throw DbException.getSyntaxError(sqlCommand, parseIndex,
"identifier");
}
I think it is a bug. What you think?
No, it is quite normal. Hibernate could not possibly make a PreparedStatement of it.
Standard JDBC has many possibilities to query schemata and such, in a database vendor independant way.
DatabaseMetaData dbMeta = connection.getMetaData();
Then getColumns can be used to receive a ResultSet of miscellaneous information.
You can try creating the required query instead of setting table name as named-parameter which won't work.
String sqlQuery = "show columns from " + tableName;
Class<?> entity = Class.forName(entityName);
session.createSQLQuery(sqlQuery);
Get the metadata information & then can retrieve required details from it.
String[] properties =
sessionFactory.getClassMetadata(entityClass).getPropertyNames();
There are several other methods available to get meta information, can refer ClassMetaData
[I haven't checked Criteria API, will update if found anything relevant, you can try it]
My problem seems to be very simple but I have hard time resolving it.
I want to alter an PostgreSQL sequence using Hibernate via native sql query (other solutions are also welcomed) using next code:
Query query = getSession()
.createSQLQuery("ALTER SEQUENCE users_id_seq RESTART WITH ?")
.setInteger(0, 1);
query.executeUpdate();
But I am getting this error:
Hibernate:
ALTER SEQUENCE users_id_seq RESTART WITH ?
hibernate.engine.jdbc.spi.SqlExceptionHelper - SQL Error: 0, SQLState: 42601
hibernate.engine.jdbc.spi.SqlExceptionHelper - ERROR: syntax error at or near "$1"
Best I'm aware, you cannot prepare that statement.
If hibernate allows it, emulate the prepared statement, instead of sending it to the server. If not, sanitize the variable and issue the final statement directly.
Alternatively, wrap it in a function with dynamic SQL:
http://www.postgresql.org/docs/current/static/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN
I have to retrieve data from a table in db2 using jpa
after all configuration and mapping
when I try to execute a query using the entity manager I get errors don't know where is the problem exactly.
the message error :Error 500: <openjpa-2.1.1-SNAPSHOT-r422266:1141200 fatal general error> org.apache.openjpa.persistence.PersistenceException: DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, SQLERRMC=DB2ADMIN.CATEGORIE, DRIVER=4.8.86 {prepstmnt 85179437 SELECT t0.CODE_CAT, t0.LIBELLE_CAT FROM CATEGORIE t0 } [code=-204, state=42704]SQLCA OUTPUT[Errp=SQLNQ1FC, Errd=-2145779603, 0, 0, 0, -10, 0] DB2 SQL Error: SQLCODE=-204, SQLSTATE=42704, SQLERRMC=DB2ADMIN.CATEGORIE, DRIVER=4.8.86 DB2 SQL Error: SQLCODE=-727, SQLSTATE=56098, SQLERRMC=2;-204;42704;DB2ADMIN.CATEGORIE, DRIVER=4.8.86 DB2 SQL Error: SQLCODE=-727, SQLSTATE=56098, SQLERRMC=2;-204;42704;DB2ADMIN.CATEGORIE, DRIVER=4.8.86 FailedObject: select c from Categorie c [java.lang.String]
I had the same problem and i resolved it by adding Schema in my entity :
#Entity
#Table(name="MyTable", schema="MySchemaName")
public class MyClass implements Serializable {
...
}
From the SQLSTATE messages page, the first error (SQLCODE=-204, SQLSTATE=42704) is "An undefined object or constraint name was detected". The second error (SQLCODE=-727, SQLSTATE=56098) is "An error occurred during implicit rebind, recompile, or revalidation.", which probably stems from the -204.
-204 usually means that either the table name is spelled wrong, or it can't find the table for some reason. I don't see a schema on the SQL generated there (SELECT t0.CODE_CAT, t0.LIBELLE_CAT FROM CATEGORIE t0), so perhaps you need to add that.
I'm trying to sort a resultset using the SQL statement Order by using JPA, on a datetime column data type with this string, on a Mysql database:
Query query = em.createQuery("SELECT e FROM Events e Order by e.EventDateTime;");
Using the createQuery method java returns the error:
SEVERE: Local Exception Stack:
Exception [EclipseLink-8030] (Eclipse Persistence Services - 2.3.0.v20110604-r9504):
org.eclipse.persistence.exceptions.JPQLException
Exception Description: Error compiling the query [Events.findByGameId: SELECT e FROM Events e WHERE e.gameId =
:gameId ORDER BY e.EventDateTime DESC], line 1, column 59: unknown state or association field [EventDateTime] of class [com.jogogestao.entity.Events].
at org.eclipse.persistence.exceptions.JPQLException.unknownAttribute(JPQLException.java:457)
at org.eclipse.persistence.internal.jpa.parsing.DotNode.validate(DotNode.java:88)
at org.eclipse.persistence.internal.jpa.parsing.OrderByItemNode.validate(OrderByItemNode.java:52)
at org.eclipse.persistence.internal.jpa.parsing.OrderByNode.validate(OrderByNode.java:61)
at org.eclipse.persistence.internal.jpa.parsing.ParseTree.validate(ParseTree.java:210)
I tried sorting by the integer type primary and all runs ok...but this is not what I want of course.
Using createNativeQuery the statement runs ok...
Query query = em.createNativeQuery("SELECT * FROM Events Order by EventDateTime;");
The only problem is that the return object is not an Events type object (from the entity) and I can't convert to this type.
Maybe the problem is that JPA does not support sorting on datetime fields?
How can I get around this?
I'm using Netbeans 7.0.1, Glassfish 3.1.1, MySql 5.5.19 Community Server (GPL) and mysql-connector-java-5.1.15-bin.jar.
Thanks!
SELECT e FROM Event e ORDER BY e.eventDateTime
you don't have * - you have to specify the entity you select
don't put a semicolon at the end
use all-lower-case keywords, capital-case entity names, and lower-camel-case property names
name the entity in singular, not plural (Event vs Events)
The message is clear: you don't have an EventDateTime mapped property (or field, if fields are mapped directly) in the entity Events. If you respect the Java conventions, the field/property should be named eventDateTime, and not EventDateTime.