SQL result limit from Java application with spring-boot and DB2 database - java

I'm trying to limit the sql result from some statements, for example to 100 from an application in Java using spring-boot, and a DB2 database in an AS400.
I've tryied this two things, extending a CrudRepository
public List<AcumuladoEstadistico> findFirst10BySincroEstado(String aEstado);
and also this
#Query(name="FROM AcumuladoEstadistico a WHERE a.sincroEstado = ?1 limit 5", countQuery="10")
Iterable<AcumuladoEstadistico> findFirst10BySincroEstado(String aEstado);
but in both cases I have the following error
Caused by: java.sql.SQLException: [SQL0104] Símbolo LIMIT no válido. Símbolos válidos: FOR SKIP WITH FETCH ORDER UNION EXCEPT OPTIMIZE.
at com.ibm.as400.access.JDError.throwSQLException(JDError.java:650)
at com.ibm.as400.access.JDError.throwSQLException(JDError.java:621)
at com.ibm.as400.access.AS400JDBCStatement.commonPrepare(AS400JDBCStatement.java:1557)
at com.ibm.as400.access.AS400JDBCPreparedStatement.(AS400JDBCPreparedStatement.java:193)
at com.ibm.as400.access.AS400JDBCConnection.prepareStatement(AS400JDBCConnection.java:2025)
at com.ibm.as400.access.AS400JDBCConnection.prepareStatement(AS400JDBCConnection.java:1824)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:126)
at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108)
at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:81)
at com.sun.proxy.$Proxy61.prepareStatement(Unknown Source)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:162)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:186)
... 69 more
Why I have this problem, maybe Hibernate doesn't create the statement properly for DB2? What can I do?
Thanks a lot!

Finally I've found the problem, I was using an incorrect dialect in the properties of sping
Thanks a lot!

Related

Writing a Stored Function in Java (JDBC)

In attempting to test the callable procedure in java, I have ran across an error when attempting to call a stored procedure that reports the sign of a given input parameter (int)
CallableStatement cstmt = con.prepareCall("{CALL sign(?,"+testVal+")}");
cstmt.registerOutParameter(1, Types.INTEGER);
The stacktrace reads:
java.sql.SQLException: [Cloudera][JDBC](11420) Error, parameter metadata not populated.
at com.cloudera.hiveserver2.exceptions.ExceptionConverter.toSQLException(Unknown Source)
at com.cloudera.hiveserver2.jdbc.common.SPreparedStatement.<init>(Unknown Source)
at com.cloudera.hiveserver2.jdbc.common.SCallableStatement.<init>(Unknown Source)
at com.cloudera.hiveserver2.jdbc.common4.C4SCallableStatement.<init>(Unknown Source)
at com.cloudera.hiveserver2.jdbc.jdbc41.S41CallableStatement.<init>(Unknown Source)
at com.cloudera.hiveserver2.jdbc.jdbc41.JDBC41ObjectFactory.createCallableStatement(Unknown Source)
at com.cloudera.hiveserver2.hive.jdbc41.HiveJDBC41ObjectFactory.createCallableStatement(Unknown Source)
at com.cloudera.hiveserver2.jdbc.common.SConnection.prepareCall(Unknown Source)
at TestMethods.callableStatement(TestMethods.java:263)
at HiveJdbcGeneralTest.testTableCreation(HiveJdbcGeneralTest.java:113)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at
From the error message I think you are trying to write stored procedure for Hive.
In this case as you can see HPL/SQL != PL/SQL.
The right syntax of a stored procedure can be found here.

How to resolve "Caused by: org.hibernate.HibernateException: Unable to access lob stream"

I have recently Upgraded my application.
Upgradation details:
- Java 6 to Java 8
- Hibernate 3 to Hibernate 3.6.10
- Spring 2.5 to Spring 4
- JBoss EAP 6 to JBoss EAP 7
I am trying to save some values which include some text values and files(Clob). The data is getting saved but I am getting an exception on the next hibernate operation.
Caused by: org.hibernate.HibernateException: Unable to access lob stream
at org.hibernate.type.descriptor.java.ClobTypeDescriptor.unwrap(ClobTypeDescriptor.java:117)
at org.hibernate.type.descriptor.java.ClobTypeDescriptor.unwrap(ClobTypeDescriptor.java:46)
at org.hibernate.type.descriptor.sql.ClobTypeDescriptor$3$1.doBind(ClobTypeDescriptor.java:83)
at org.hibernate.type.descriptor.sql.BasicBinder.bind(BasicBinder.java:91)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:283)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:278)
at org.hibernate.type.AbstractSingleColumnStandardBasicType.nullSafeSet(AbstractSingleColumnStandardBasicType.java:89)
at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:2184)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2559)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2495)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2822)
at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:113)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:185)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at com.honeywell.cdd.dao.RptGrpDAOImpl.removeUnConfigGrpMTDT(RptGrpDAOImpl.java:2373)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.orm.hibernate3.HibernateInterceptor.invoke(HibernateInterceptor.java:112)
... 68 more
Caused by: java.sql.SQLException: could not reset reader
at org.hibernate.engine.jdbc.ClobProxy.resetIfNeeded(ClobProxy.java:178)
at org.hibernate.engine.jdbc.ClobProxy.getCharacterStream(ClobProxy.java:89)
at org.hibernate.engine.jdbc.ClobProxy.invoke(ClobProxy.java:121)
at com.sun.proxy.$Proxy133.getCharacterStream(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.engine.jdbc.SerializableClobProxy.invoke(SerializableClobProxy.java:74)
at com.sun.proxy.$Proxy132.getCharacterStream(Unknown Source)
at org.hibernate.type.descriptor.java.ClobTypeDescriptor.unwrap(ClobTypeDescriptor.java:114)
... 98 more
I am not able to find out exact cause of this exception.
> The Same Code is working fine in the older configuration
"The Same Code is working fine in the older configuration"
is not really relevant ... unless you want to submit a but report to someone.
Lets look at what the nested exception:
Caused by: java.sql.SQLException: could not reset reader
The stacktrace indicates that something is calling getCharacterStream() on a Clob proxy and that is failing when the proxy attempts to reset the proxy's reader. The failure is (presumably) occurring because the JDBC object wrapped by the proxy doesn't allow a reader to be reset.
So why is this happening?
Again ... presumably ... something in your application has tried to call getCharacterStream() twice on a Clob proxy.
My guess is that you are (implicitly) using Clob objects as if they were in-memory files ... to avoid reading them when you don't need to. Except that sometimes you need to, and this is interfering with the persisting.

h2 concurrent update in embedded mode

I'm using Hibernate 1.4.191 along with Hibernate 4.3.1. My h2 connection url is dbc:h2:file:./h2/myDB - which is an embedded DB without MULTI_THREADED enabled. I'm running with MVCC on - as this is the default setting for 1.4.191.
Using this configuration in my application, I got the following stack trace while trying to execute an update HQL statement:
2017-07-11 19:38:48 SEVERE Could not set rounding style. org.hibernate.PessimisticLockException: could not execute statement
at org.hibernate.dialect.H2Dialect$2.convert(H2Dialect.java:342)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:190)
at org.hibernate.hql.internal.ast.exec.BasicExecutor.doExecute(BasicExecutor.java:109)
at org.hibernate.hql.internal.ast.exec.BasicExecutor.execute(BasicExecutor.java:78)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.executeUpdate(QueryTranslatorImpl.java:445)
at org.hibernate.engine.query.spi.HQLQueryPlan.performExecuteUpdate(HQLQueryPlan.java:347)
at org.hibernate.internal.SessionImpl.executeUpdate(SessionImpl.java:1282)
at org.hibernate.internal.QueryImpl.executeUpdate(QueryImpl.java:118)
at de.oktopos.dataBase.receipts.converter.ReceiptConverter$29.runOperation(ReceiptConverter.java:1214)
at de.oktopos.dataBase.receipts.converter.ReceiptConverter$29.runOperation(ReceiptConverter.java:1210)
at de.oktopos.dataBase.tools.DatabaseOperationRunner.run(DatabaseOperationRunner.java:71)
at de.oktopos.dataBase.receipts.converter.ReceiptConverter.setRoundingStyle(ReceiptConverter.java:1226)
at de.oktopos.dataBase.receipts.converter.ReceiptCacheWriter.setRoundingStyle(ReceiptCacheWriter.java:99)
at de.oktopos.oktoDeskService.remote.OktoDeskModel.setRoundingStyle(OktoDeskModel.java:841)
at net.oktopos.cashdesk.DeskModelProcessor.setRoundingStyle(DeskModelProcessor.java:1648)
at sun.reflect.GeneratedMethodAccessor37.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.rmi.server.UnicastServerRef.dispatch(Unknown Source)
at sun.rmi.transport.Transport$1.run(Unknown Source)
at sun.rmi.transport.Transport$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.lambda$run$0(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.h2.jdbc.JdbcSQLException: Zeitüberschreitung beim Versuch die Tabelle zu sperren
Timeout trying to lock table ; SQL statement:
update Receipt set turnoverType=? [50200-191]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:168)
at org.h2.command.Command.filterConcurrentUpdate(Command.java:307)
at org.h2.command.Command.executeUpdate(Command.java:260)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:160)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:146)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:187)
... 29 more
Caused by: org.h2.jdbc.JdbcSQLException: Gleichzeitige Änderung in Tabelle "RECEIPT": eine andere Transaktion hat den gleichen Datensatz geändert oder gelöscht
Concurrent update in table "RECEIPT": another transaction has updated or deleted the same row [90131-191]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345)
at org.h2.message.DbException.get(DbException.java:168)
at org.h2.mvstore.db.MVTable.convertException(MVTable.java:898)
at org.h2.mvstore.db.MVSecondaryIndex.remove(MVSecondaryIndex.java:247)
at org.h2.mvstore.db.MVTable.removeRow(MVTable.java:677)
at org.h2.table.Table.updateRows(Table.java:487)
at org.h2.command.dml.Update.update(Update.java:145)
at org.h2.command.CommandContainer.update(CommandContainer.java:98)
at org.h2.command.Command.executeUpdate(Command.java:258)
... 32 more
Caused by: java.lang.IllegalStateException: Entry is locked [1.4.191/101]
at org.h2.mvstore.DataUtils.newIllegalStateException(DataUtils.java:773)
at org.h2.mvstore.db.TransactionStore$TransactionMap.set(TransactionStore.java:1031)
at org.h2.mvstore.db.TransactionStore$TransactionMap.remove(TransactionStore.java:989)
at org.h2.mvstore.db.MVSecondaryIndex.remove(MVSecondaryIndex.java:241)
... 37 more
Im trying to understand how this is possible. The stack trace seems to say that a lock could not be acquired because of another connection (50200). In particular it says that another connection concurrently updated the table (90131). But there can only be one connection because the database is embedded. Am I missing something here?
The the HQL query is basically executed as follows (minus error handling boilerplate, DBReceipt maps to receipt):
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.createQuery("UPDATE DBReceipt SET turnovertype = :turnovertype")
.setParameter("turnovertype", turnovertype)
.executeUpdate();
transaction.commit();
session.close();
There are of course many other database writes/reads in the background on different threads, but all use the same connection.
The error kept happening when the above part of the code was called. Even restarting the application did not help - the next call of the code would cause the same exception. Only dropping the DB helped.
I found the likely source of the problem after looking arround a bit in my code base.
I was namely creating a LockRequest and locking the a receipt in the receipt table. If this lock is never let go (because the transaction ends up in an infinite loop), then any update on the receipt table afterwards would lead to the stack trace above.
I solved the problem by removing the LockRequest (I couldn't find the source of the infinite loop). This was possible because we recently moved to locking that receipt on an application level, and also because there would be no problems in our application with optimistic locking.
Another work around to this problem would be to add a timeout to the lock, transaction, or session. However, my enviroment doesn't seem to support any of these - at least none of them worked in my tests.

Generating HSQLDB tables in memory from JPA/EclipseLink (no files)

I have JPA2 with EclipseLink 2.4, and I'm trying to implement an in-memory database using HSQLDB. I have been able to create a file implementation of the hsqldb using
jdbc:hsqldb:file:./databases/test;shutdown=true;files_readonly=true
But when I try to use jdbc:hsqldb:mem:tableName, I get the following message:
Stacktrace:
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse
Persistence Services - 2.4.0.v20120608-r11652):
org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLSyntaxErrorException: user lacks privilege or object
not found: EFFECTIVITY
Error Code: -5501
Call: INSERT INTO EFFECTIVITY (HULL) VALUES (?)
bind => [1 parameter bound]
Query: InsertObjectQuery(101)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.flush
(EntityManagerImpl.java:804)
at com.gdeb.touchtable.db.TestJPAEntities.testTTTouch(TestJPAEntities.java:93)
..............
Caused by: org.hsqldb.HsqlException: user lacks privilege or object not found:
EFFECTIVITY
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.error.Error.error(Unknown Source)
at org.hsqldb.SchemaManager.getTable(Unknown Source)
at org.hsqldb.ParserDQL.readTableName(Unknown Source)
at org.hsqldb.ParserDQL.readRangeVariableForDataChange(Unknown Source)
at org.hsqldb.ParserDML.compileInsertStatement(Unknown Source)
at org.hsqldb.ParserCommand.compilePart(Unknown Source)
at org.hsqldb.ParserCommand.compileStatement(Unknown Source)
at org.hsqldb.Session.compileStatement(Unknown Source)
at org.hsqldb.StatementManager.compile(Unknown Source)
at org.hsqldb.Session.execute(Unknown Source)
... 63 more
From what I read, the data model should be generated automagically, but I have only seen examples with Hibernate. Is there a way to link the JPA data-model and create it using the memory mode of HSQLDB?
If what is missing are the tables, you need to set the eclipselink.ddl-generation property with a value of "create-tables" to have Eclipselink create them for you. An example is posted here: http://wiki.eclipse.org/EclipseLink/Examples/JPA/DDL

"Different objects with the same identifiers" error

I'm using in a Java project RMI + Hibernate and I'm experiencing problems related to NotUniqueException with the error "Different objects with the same identifier".
I've got several doubts:
I'm pretty surre that I don't copy nor create new objects with the same ide
ntifiers. Is it possible that RMI creates a new object from another one when I use it?
Which method is using Hibernate to know that two objects are the same? equals?
I know that Serializable is related to Hibernate but I don't know in what way?
How can I solve the "Differents objects error" using RMI at the same time?
Is it correct every time I use delete or save over an object use merge before?
The stack traces is:
org.orm.PersistentException: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [dcl.Administrador#10]
at org.orm.PersistentSession.saveOrUpdate(PersistentSession.java:648)
at org.orm.PersistentManager.saveObject(PersistentManager.java:274)
at dcl.AdministradorDAO.save(AdministradorDAO.java:240)
at dcl.BdAdministrador.guardarAdministrador(BdAdministrador.java:62)
at dcl.BdAdministrador.actualizarAdministrador(BdAdministrador.java:109)
at dcl.BdPrincipal.actualizarAdministrador(BdPrincipal.java:555)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.rmi.server.UnicastServerRef.dispatch(Unknown Source)
at sun.rmi.transport.Transport$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at sun.rmi.transport.Transport.serviceCall(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport.handleMessages(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run0(Unknown Source)
at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Thanks in advance.
If you're doing something like returning a hibernate object from an RMI method, then passing it back into another one, then you'll potentially need to reattach the object to the session. (see What is the proper way to re-attach detached objects in Hibernate?).
Perhaps give some more info on what you're attempting if this doesn't help.

Categories