I am frequently getting this exception :
javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not prepare statement
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:147)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1423)
at org.hibernate.query.Query.getResultList(Query.java:146)
at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.getResultList(CriteriaQueryTypeQueryAdapter.java:72)
at com.inmobi.programmatics.myservice.dao.impl.AbstractDAOImpl.getByIds(AbstractDAOImpl.java:117)
Caused by: org.hibernate.exception.GenericJDBCException: could not prepare statement
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:182)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:148)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1940)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1909)
Caused by: java.sql.SQLException: Connection is closed
at com.zaxxer.hikari.pool.ProxyConnection$ClosedConnection$1.invoke(ProxyConnection.java:469)
at com.sun.proxy.$Proxy66.prepareStatement(Unknown Source)
at com.zaxxer.hikari.pool.ProxyConnection.prepareStatement(ProxyConnection.java:310)
at com.zaxxer.hikari.pool.HikariProxyConnection.prepareStatement(HikariProxyConnection.java)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:146)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:172)
Here is my configuration for using HikariCP with JPA Hibernate :
JpaPersistModule jpaPersistModule = new JpaPersistModule("persistenceConfig");
final Map<String, Object> properties = new HashMap<>();
properties.put("hibernate.hikari.dataSource.url",
"jdbc:postgresql://" + configurationData.getDBHost() + ":" + configurationData.getDBPort()
+ "/" + configurationData.getDBName() + "?stringtype=unspecified");
properties.put("hibernate.hikari.dataSource.user", configurationData.getDBUser());
properties.put("hibernate.hikari.dataSource.password", configurationData.getDBPassword());
properties.put("hibernate.hikari.minimumIdle", "2");
properties.put("hibernate.hikari.maximumPoolSize", "8");
properties.put("hibernate.hikari.connectionTimeout", "30000");
properties.put("hibernate.hikari.idleTimeout", "60000");
properties.put("hibernate.hikari.poolName", "master_pool");
properties.put("hibernate.hikari.leakDetectionThreshold", "60000");
properties.put("hibernate.hikari.maxLifetime", "600000");
properties.put("hibernate.hikari.connectionTestQuery", "select 1");
properties.put("hibernate.hikari.connectionInitSql", "select 1");
Here is my peristence.xml for JPA:
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="persistenceConfig" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL94Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="validate"/>
<property name="hibernate.jdbc.time_zone" value="UTC"/>
<property name="hibernate.jdbc.batch_size" value="25"/>
<property name="hibernate.connection.provider_class" value="org.hibernate.hikaricp.internal.HikariCPConnectionProvider"/>
<property name="hibernate.hikari.dataSourceClassName" value="org.postgresql.ds.PGSimpleDataSource"/>
</properties>
</persistence-unit>
</persistence>
I have checked idle_in_transaction_session_timeout in postgres db is 1 hour. It means there is no issue from db side.
I have tried to adjust hikaricp configuration. But it is not helping.
Initially I thought it maybe because of leak connection for which I added leakDetectionThreshold to 60 sec.
Then again I thought it maybe because of getting invalid connection from pool for which I have set connectionTestQuery. But it's also not helping.
I have checked there is maximum 1 or 2 connection are active at any time. So it can't be maxpool size issue.
I have looked into this stackoverflow question. It is not making any sense for my problem statement as I am using entitymanager with Guice Transactional.So I don't need to care about connection closing which will take care by Guice Transactional.
Can anyone help with it ?
Related
I'm trying to use sqlite as persistence layer in my application and interact with it via JPA. But whenever I connect either for reading or for writing I get java.sql.SQLException.
I use Websphere Liberty webProfile8 19.0.0.1 with EclipseLink 2.6.8 as JPA provider.
There is a load script which puts some initial data to TEST_ENTITY table and it works with no issues. Probably the way how JPA manages db connections for entities is different.
If I switch to Apache Derby datasource everything works just fine.
Did anybody face something similar?
server.xml:
<library id="sqlitelib">
<fileset dir="${shared.resource.dir}/libs" id="sqlite-jdbc" includes="sqlite-jdbc-3.23.1.jar"/>
</library>
<dataSource id="annodb"
type="javax.sql.DataSource"
isolationLevel="TRANSACTION_SERIALIZABLE"
jndiName="jdbc/annodb">
<jdbcDriver
javax.sql.ConnectionPoolDataSource="org.sqlite.javax.SQLiteConnectionPoolDataSource"
javax.sql.DataSource="org.sqlite.SQLiteDataSource"
libraryRef="sqlitelib"/>
<properties URL="jdbc:sqlite:c:/__anno.db"/>
</dataSource>
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="annodb">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/annodb</jta-data-source>
<!-- non-jta-data-source>jdbc/annodb</non-jta-data-source-->
<class>com.ibm.zurich.ainews.domain.anno.entities.TestEntity</class>
<properties>
<!--property name="eclipselink.ddl-generation.output-mode" value="both"/-->
<property name="eclipselink.logging.level" value="ALL"/>
<property name="eclipselink.logging.logger" value="ServerLogger"/>
<property name="eclipselink.create-ddl-jdbc-file-name" value="createSchemaDDL.sql"/>
<property name="eclipselink.drop-ddl-jdbc-file-name" value="dropSchemaDDL.sql"/>
<property name="eclipselink.weaving" value="false"/>
<property name="javax.persistence.schema-generation.scripts.create-target" value="create.ddl"/>
<property name="javax.persistence.sql-load-script-source" value="load.sql"/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<property name="javax.persistence.schema-generation.scripts.action" value="drop-and-create"/>
<property name="eclipselink.jdbc.native-sql" value="false"/>
<property name="javax.persistence.schema-generation.scripts.drop-target" value="drop.ddl"/>
</properties>
</persistence-unit>
</persistence>
full stack trace:
[2/21/19 23:33:32:462 CET] 000000e0 connection 3 client acquired: 642755657
[2/21/19 23:33:32:465 CET] 000000e0 transaction 3 TX binding to tx mgr, status=STATUS_ACTIVE
[2/21/19 23:33:32:465 CET] 000000e0 transaction 3 acquire unit of work: -1982630449
[2/21/19 23:33:32:465 CET] 000000e0 transaction 3 begin unit of work flush
[2/21/19 23:33:32:465 CET] 000000e0 transaction 3 end unit of work flush
[2/21/19 23:33:32:465 CET] 000000e0 query 3 Execute query ReadAllQuery(name="TestEntity.findAll" referenceClass=TestEntity sql="SELECT PKEY, FIELD FROM TEST_ENTITY")
[2/21/19 23:33:32:466 CET] 000000e0 connection 3 Connection acquired from connection pool [read].
[2/21/19 23:33:32:466 CET] 000000e0 connection 3 reconnecting to external connection pool
[2/21/19 23:33:32:467 CET] 000000e0 sql 3 SELECT PKEY, FIELD FROM TEST_ENTITY
[2/21/19 23:33:32:477 CET] 000000e0 connection 3 Connection released to connection pool [read].
[2/21/19 23:33:32:477 CET] 000000e0 eclipselink W CWWJP9991W: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.8.WAS-v20181218-0accd7f): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: statement is not executing
Error Code: 0
Query: ReadAllQuery(name="TestEntity.findAll" referenceClass=TestEntity sql="SELECT PKEY, FIELD FROM TEST_ENTITY")
[2/21/19 23:33:32:478 CET] 000000e0 BusinessExcep E CNTR0020E: EJB threw an unexpected (non-declared) exception during invocation of method "testRead" on bean "BeanId(ear#war-0.0.1-SNAPSHOT.war#AnnoMgr, null)". Exception data: javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.8.WAS-v20181218-0accd7f): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: statement is not executing
Error Code: 0
Query: ReadAllQuery(name="TestEntity.findAll" referenceClass=TestEntity sql="SELECT PKEY, FIELD FROM TEST_ENTITY")
at org.eclipse.persistence.internal.jpa.QueryImpl.getDetailedException(QueryImpl.java:382)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:260)
at org.eclipse.persistence.internal.jpa.QueryImpl.getResultList(QueryImpl.java:473)
at com.ibm.zurich.ainews.domain.anno.mgr.AnnoMgr.testRead(AnnoMgr.java:72)
at sun.reflect.GeneratedMethodAccessor1196.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Method.java:508)
at com.ibm.ejs.container.EJSContainer.invokeProceed(EJSContainer.java:4886)
at com.ibm.ejs.container.interceptors.InvocationContextImpl.proceed(InvocationContextImpl.java:592)
at com.ibm.ws.cdi.ejb.impl.InterceptorChain.proceed(InterceptorChain.java:119)
at com.ibm.ws.cdi.ejb.impl.EJBCDIInterceptorWrapper.invokeInterceptors(EJBCDIInterceptorWrapper.java:131)
at com.ibm.ws.cdi.ejb.impl.EJBCDIInterceptorWrapper.aroundInvoke(EJBCDIInterceptorWrapper.java:54)
at sun.reflect.GeneratedMethodAccessor1195.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Method.java:508)
at com.ibm.ejs.container.interceptors.InterceptorProxy.invokeInterceptor(InterceptorProxy.java:189)
at com.ibm.ejs.container.interceptors.InvocationContextImpl.proceed(InvocationContextImpl.java:577)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:64)
at com.ibm.ws.cdi.ejb.interceptor.WeldSessionBeanInterceptorWrapper.aroundInvoke(WeldSessionBeanInterceptorWrapper.java:58)
at sun.reflect.GeneratedMethodAccessor1194.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Method.java:508)
at com.ibm.ejs.container.interceptors.InterceptorProxy.invokeInterceptor(InterceptorProxy.java:189)
at com.ibm.ejs.container.interceptors.InvocationContextImpl.proceed(InvocationContextImpl.java:577)
at com.ibm.ejs.container.interceptors.InvocationContextImpl.doAroundInterceptor(InvocationContextImpl.java:298)
at com.ibm.ejs.container.interceptors.InvocationContextImpl.doAroundInvoke(InvocationContextImpl.java:267)
at com.ibm.ejs.container.EJSContainer.invoke(EJSContainer.java:4788)
at com.ibm.zurich.ainews.domain.anno.mgr.EJSLocalNSLAnnoMgr_99272aa0.testRead(EJSLocalNSLAnnoMgr_99272aa0.java)
at com.ibm.zurich.ainews.api.stories.svc.TestSvc.testAnnoDB(TestSvc.java:71)
at sun.reflect.GeneratedMethodAccessor1184.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Method.java:508)
at com.ibm.ejs.container.EJSContainer.invokeProceed(EJSContainer.java:4886)
at com.ibm.ejs.container.interceptors.InvocationContextImpl.proceed(InvocationContextImpl.java:592)
at com.ibm.ws.cdi.ejb.impl.InterceptorChain.proceed(InterceptorChain.java:119)
at com.ibm.ws.cdi.ejb.impl.EJBCDIInterceptorWrapper.invokeInterceptors(EJBCDIInterceptorWrapper.java:131)
at com.ibm.ws.cdi.ejb.impl.EJBCDIInterceptorWrapper.aroundInvoke(EJBCDIInterceptorWrapper.java:54)
at sun.reflect.GeneratedMethodAccessor1195.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Method.java:508)
at com.ibm.ejs.container.interceptors.InterceptorProxy.invokeInterceptor(InterceptorProxy.java:189)
at com.ibm.ejs.container.interceptors.InvocationContextImpl.proceed(InvocationContextImpl.java:577)
at org.jboss.weld.ejb.AbstractEJBRequestScopeActivationInterceptor.aroundInvoke(AbstractEJBRequestScopeActivationInterceptor.java:64)
at com.ibm.ws.cdi.ejb.interceptor.WeldSessionBeanInterceptorWrapper.aroundInvoke(WeldSessionBeanInterceptorWrapper.java:58)
at sun.reflect.GeneratedMethodAccessor1194.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Method.java:508)
at com.ibm.ejs.container.interceptors.InterceptorProxy.invokeInterceptor(InterceptorProxy.java:189)
at com.ibm.ejs.container.interceptors.InvocationContextImpl.proceed(InvocationContextImpl.java:577)
at com.ibm.ejs.container.interceptors.InvocationContextImpl.doAroundInterceptor(InvocationContextImpl.java:298)
at com.ibm.ejs.container.interceptors.InvocationContextImpl.doAroundInvoke(InvocationContextImpl.java:267)
at com.ibm.ejs.container.EJSContainer.invoke(EJSContainer.java:4788)
at com.ibm.zurich.ainews.api.stories.svc.EJSLocalNSLTestSvc_32d4537b.testAnnoDB(EJSLocalNSLTestSvc_32d4537b.java)
at sun.reflect.GeneratedMethodAccessor1184.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Method.java:508)
at com.ibm.ws.jaxrs20.ejb.JaxRsFactoryBeanEJBCustomizer.serviceInvoke(JaxRsFactoryBeanEJBCustomizer.java:333)
at com.ibm.ws.jaxrs20.server.LibertyJaxRsServerFactoryBean.performInvocation(LibertyJaxRsServerFactoryBean.java:637)
at com.ibm.ws.jaxrs20.server.LibertyJaxRsInvoker.performInvocation(LibertyJaxRsInvoker.java:160)
at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:96)
at com.ibm.ws.jaxrs20.server.LibertyJaxRsInvoker.invoke(LibertyJaxRsInvoker.java:273)
at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:191)
at com.ibm.ws.jaxrs20.server.LibertyJaxRsInvoker.invoke(LibertyJaxRsInvoker.java:444)
at org.apache.cxf.jaxrs.JAXRSInvoker.invoke(JAXRSInvoker.java:101)
at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:61)
at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:99)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:309)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:124)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:271)
at com.ibm.ws.jaxrs20.endpoint.AbstractJaxRsWebEndpoint.invoke(AbstractJaxRsWebEndpoint.java:134)
at com.ibm.websphere.jaxrs.server.IBMRestServlet.handleRequest(IBMRestServlet.java:146)
at com.ibm.websphere.jaxrs.server.IBMRestServlet.doGet(IBMRestServlet.java:112)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at com.ibm.websphere.jaxrs.server.IBMRestServlet.service(IBMRestServlet.java:96)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1255)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:743)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:440)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1221)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1005)
at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:75)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:923)
at com.ibm.ws.webcontainer.osgi.DynamicVirtualHost$2.run(DynamicVirtualHost.java:279)
at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink$TaskWrapper.run(HttpDispatcherLink.java:1047)
at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink.wrapHandlerAndExecute(HttpDispatcherLink.java:417)
at com.ibm.ws.http.dispatcher.internal.channel.HttpDispatcherLink.ready(HttpDispatcherLink.java:376)
at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:532)
at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.handleNewRequest(HttpInboundLink.java:466)
at com.ibm.ws.http.channel.internal.inbound.HttpInboundLink.processRequest(HttpInboundLink.java:331)
at com.ibm.ws.http.channel.internal.inbound.HttpICLReadCallback.complete(HttpICLReadCallback.java:70)
at com.ibm.ws.channel.ssl.internal.SSLReadServiceContext$SSLReadCompletedCallback.complete(SSLReadServiceContext.java:1803)
at com.ibm.ws.tcpchannel.internal.WorkQueueManager.requestComplete(WorkQueueManager.java:501)
at com.ibm.ws.tcpchannel.internal.WorkQueueManager.attemptIO(WorkQueueManager.java:571)
at com.ibm.ws.tcpchannel.internal.WorkQueueManager.workerRun(WorkQueueManager.java:926)
at com.ibm.ws.tcpchannel.internal.WorkQueueManager$Worker.run(WorkQueueManager.java:1015)
at com.ibm.ws.threading.internal.ExecutorServiceImpl$RunnableWrapper.run(ExecutorServiceImpl.java:239)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1153)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.lang.Thread.run(Thread.java:785)
Caused by: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.8.WAS-v20181218-0accd7f): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLException: statement is not executing
Error Code: 0
Query: ReadAllQuery(name="TestEntity.findAll" referenceClass=TestEntity sql="SELECT PKEY, FIELD FROM TEST_ENTITY")
at org.eclipse.persistence.exceptions.DatabaseException.sqlException(DatabaseException.java:331)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:713)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.executeCall(DatabaseAccessor.java:560)
at org.eclipse.persistence.internal.sessions.AbstractSession.basicExecuteCall(AbstractSession.java:2061)
at org.eclipse.persistence.sessions.server.ServerSession.executeCall(ServerSession.java:586)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:262)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeCall(DatasourceCallQueryMechanism.java:248)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.executeSelectCall(DatasourceCallQueryMechanism.java:319)
at org.eclipse.persistence.internal.queries.DatasourceCallQueryMechanism.selectAllRows(DatasourceCallQueryMechanism.java:715)
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectAllRowsFromTable(ExpressionQueryMechanism.java:2767)
at org.eclipse.persistence.internal.queries.ExpressionQueryMechanism.selectAllRows(ExpressionQueryMechanism.java:2720)
at org.eclipse.persistence.queries.ReadAllQuery.executeObjectLevelReadQuery(ReadAllQuery.java:559)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeDatabaseQuery(ObjectLevelReadQuery.java:1175)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:911)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1134)
at org.eclipse.persistence.queries.ReadAllQuery.execute(ReadAllQuery.java:460)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:1222)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2899)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1863)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1845)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1810)
at org.eclipse.persistence.internal.jpa.QueryImpl.executeReadQuery(QueryImpl.java:258)
... 89 more
Caused by: java.sql.SQLException: statement is not executing
at org.sqlite.core.CoreStatement.checkOpen(CoreStatement.java:50)
at org.sqlite.jdbc3.JDBC3PreparedStatement.clearParameters(JDBC3PreparedStatement.java:37)
at com.ibm.ws.rsadapter.jdbc.WSJdbcPreparedStatement.closeWrapper(WSJdbcPreparedStatement.java:316)
at com.ibm.ws.rsadapter.jdbc.WSJdbcObject.close(WSJdbcObject.java:152)
at com.ibm.ws.rsadapter.jdbc.WSJdbcObject.close(WSJdbcObject.java:110)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.closeStatement(DatabaseAccessor.java:410)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.releaseStatement(DatabaseAccessor.java:1674)
at org.eclipse.persistence.internal.databaseaccess.DatabaseAccessor.basicExecuteCall(DatabaseAccessor.java:705)
... 109 more
I am writing a simple Hibernate program with Oracle as a database.
I am facing this error and I am not able to get the solution despite many trials.
I have added all hibernate jars & Oracle(ojdbc14.jar)
I have a schema as "test" in Oracle database
The username & password for Oracle is system
I have created the following files:
Student.java - POJO class with fields as rollno, name, address & setters/getters
Student.hbm.xml - Mapping file
Student.cfg.xml - Hibernate Configuration file
Test.java - Driver class
Student.cfg.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name = "connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name = "connection.url">jdbc:oracle:thin:#localhost:1521:xe</property>
<property name = "username">system</property>
<property name = "password">system</property>
<property name = "show_sql">true</property>
<property name = "dialect">org.hibernate.dialect.OracleDialect</property>
<property name = "hbm2ddl.auto">update</property>
<mapping resource = "com/alighthub/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Below is the error:
Exception in thread "main" org.hibernate.exception.GenericJDBCException: Cannot open connection
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:420)
at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:144)
at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:119)
at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:57)
at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1326)
at com.alighthub.Test.main(Test.java:16)
Caused by: java.sql.SQLException: invalid arguments in call
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:236)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:414)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:110)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:417)
... 5 more
Please suggest.
Property for username & password is incorrect in Student.cfg.xml, updated as "connection.username" & "connection.password" as below :-
<property name = "connection.username">system</property>
<property name = "connection.password">system</property>
I am learning to integrate hibernate with spring to connect to Oracle 11g using the below code. But stuck with the same error from few days. Please help me resolve this. i have tried the different solutions mentioned in other answers given for questions with the same error, but no luck.
Any relevant solutions welcome.
Thanks,
Nisha
spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="serverDatasource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" >
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url" >
<value>jdbc:oracle:thin:#10.23.225.22:1521:PRACTICE</value>
</property>
<!-- <property name="username" value="SCOTT"/>
<property name="password" value="tiger"/>-->
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.UserCredentialsDataSourceAdapter">
<property name="targetDataSource" ref="serverDatasource"/>
<property name="username"><value>SCOTT</value></property>
<property name="password"><value>tiger</value></property>
</bean>
<!-- Hibernate 5 SessionFactory bean definition -->
<bean id="Hibernate5SessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="annotatedClasses">
<list>
<value>com.springHibernate.model.Person</value>
</list>
</property>
<property name="HibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<bean id="personDao" class="com.springHibernate.dao.PersonDaoImpl">
<property name="sessionFactory" ref="Hibernate5SessionFactory"></property>
</bean>
</beans>
Main Method: SpringHibernateMain
package com.springHibernate.main;
import java.util.List;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.springHibernate.dao.PersonDao;
import com.springHibernate.model.Person;
public class SpringHibernateMain {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
PersonDao personDao = context.getBean(PersonDao.class);
Person p = new Person();
p.setId(1);
p.setName("John");
p.setCountry("United States");
personDao.save(p);
List<Person> person = personDao.listPerson();
for(Person p1 : person){
System.out.println("Person List:" + p1);
}
}
}
Stack Trace:
ERROR: Unable obtain JDBC Connection
java.sql.SQLException: invalid arguments in call
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:236)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:414)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:155)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:130)
at org.springframework.jdbc.datasource.UserCredentialsDataSourceAdapter.doGetConnection(UserCredentialsDataSourceAdapter.java:162)
at org.springframework.jdbc.datasource.UserCredentialsDataSourceAdapter.getConnection(UserCredentialsDataSourceAdapter.java:145)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.internal.SessionFactoryImpl$3.obtainConnection(SessionFactoryImpl.java:643)
at org.hibernate.hql.spi.id.IdTableHelper.executeIdTableCreationStatements(IdTableHelper.java:67)
at org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy.finishPreparation(GlobalTemporaryTableBulkIdStrategy.java:125)
at org.hibernate.hql.spi.id.global.GlobalTemporaryTableBulkIdStrategy.finishPreparation(GlobalTemporaryTableBulkIdStrategy.java:42)
at org.hibernate.hql.spi.id.AbstractMultiTableBulkIdStrategyImpl.prepare(AbstractMultiTableBulkIdStrategyImpl.java:88)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:451)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:465)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:416)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:401)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:753)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.springHibernate.main.SpringHibernateMain.main(SpringHibernateMain.java:14)
May 16, 2016 12:59:16 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 17433, SQLState: null
May 16, 2016 12:59:16 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: invalid arguments in call
Exception in thread "main" org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:111)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:97)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:87)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getPhysicalConnection(LogicalConnectionManagedImpl.java:109)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.getConnectionForTransactionManagement(LogicalConnectionManagedImpl.java:227)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.begin(LogicalConnectionManagedImpl.java:234)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcResourceLocalTransactionCoordinatorImpl$TransactionDriverControlImpl.begin(JdbcResourceLocalTransactionCoordinatorImpl.java:214)
at org.hibernate.engine.transaction.internal.TransactionImpl.begin(TransactionImpl.java:52)
at org.hibernate.internal.SessionImpl.beginTransaction(SessionImpl.java:1525)
at com.springHibernate.dao.PersonDaoImpl.save(PersonDaoImpl.java:25)
at com.springHibernate.main.SpringHibernateMain.main(SpringHibernateMain.java:24)
Caused by: java.sql.SQLException: invalid arguments in call
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:208)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:236)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:414)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:153)
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:144)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:155)
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:130)
at org.springframework.jdbc.datasource.UserCredentialsDataSourceAdapter.doGetConnection(UserCredentialsDataSourceAdapter.java:162)
at org.springframework.jdbc.datasource.UserCredentialsDataSourceAdapter.getConnection(UserCredentialsDataSourceAdapter.java:145)
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122)
at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:386)
at org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl.acquireConnectionIfNeeded(LogicalConnectionManagedImpl.java:84)
... 8 more
As It is mentioned in the Stacktrace it is unable to get the connection.
invalid arguments in call
Exception in thread "main" org.hibernate.exception.GenericJDBCException: Unable to acquire JDBC Connection
In datasource driver name should be like below
<value>oracle.jdbc.OracleDriver</value>
In procedure if we give incorrect type mapping from java type to oracle data type then we will get
org.springframework.jdbc.UncategorizedSQLException: CallableStatementCallback; uncategorized SQLException for proc SQL state [99999]; error code [17068]; Invalid argument(s) in call; nested exception is java.sql.SQLException: Invalid argument(s) in call
To fix this we need to map respective data type.
Instead
PersonDao personDao = context.getBean(PersonDao.class);
Try with
PersonDao personDao = (PersonDao) context.getBean("personDao");
So your Bean Id in spring.xml
Solved this, at last, by adding just the jars in lib/required folder of Hibernate zip file. Till then i had added all the jars in the lib folder.
I have a project use Struts2+hibernate3(c3p0),
Following is my C3P0 configuration
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="hibernate.c3p0.idle_test_period">15</property>
<property name="hibernate.c3p0.max_idle_time">10</property>
<property name="hibernate.c3p0.max_size">50</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.min_size">20</property>
<property name="hibernate.c3p0.timeout">10</property>
<property name="hibernate.c3p0.validate">true</property>
<property name="hibernate.c3p0.preferredTestQuery">select 1 from dual</property>
<property name="automaticTestTable">Test</property>
<!-- <property name="hibernate.c3p0.testConnectionOnCheckout">true</property> -->
<property name="hibernate.connection.autoReconnect">true</property>
<property name="hibernate.connection.autoReconnectForPools">true</property>
<property name="hibernate.connection.is-connection-validation-required">true</property>
My database is mysql and I can not config it (in cloud)
My problem is some time I got following message
Caused by: org.hibernate.exception.GenericJDBCException: Cannot open connection
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:126)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:114)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:52)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:449)
at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167)
at org.hibernate.jdbc.JDBCContext.connection(JDBCContext.java:142)
at org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:85)
at org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1354)
at com.rh.ws.getAllMessageAction.getAllMessage(getAllMessageAction.java:42)
... 86 more
Caused by: java.sql.SQLException: Connections could not be acquired from the underlying database!
at com.mchange.v2.sql.SqlUtils.toSQLException(SqlUtils.java:118)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:690)
at com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource.getConnection(AbstractPoolBackedDataSource.java:140)
at org.hibernate.connection.C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:78)
at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446)
... 91 more
Caused by: com.mchange.v2.resourcepool.CannotAcquireResourceException: A ResourcePool could not acquire a resource from its primary factory or source.
at com.mchange.v2.resourcepool.BasicResourcePool.awaitAvailable(BasicResourcePool.java:1422)
at com.mchange.v2.resourcepool.BasicResourcePool.prelimCheckoutResource(BasicResourcePool.java:606)
at com.mchange.v2.resourcepool.BasicResourcePool.checkoutResource(BasicResourcePool.java:526)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutAndMarkConnectionInUse(C3P0PooledConnectionPool.java:756)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool.checkoutPooledConnection(C3P0PooledConnectionPool.java:683)
The wait_timeout is 30s in my database(mysql) and it's can not change.
I try to set the max_idle_time to 20 and I discover it doesn't work.
Do I need close the connection every time? or just close the session is fine?
When you close a Session it will automatically close the underlying connection. You should also commit the Hibernate Transaction on success and rollback on failure. This will ensure that the database transaction is properly terminated.
If you don't close teh Hibernate Session, then the JDBC connection won't be released. So when all hibernate.c3p0.max_size are being in use, you'll soon get the connection acquire connection exception.
One other cause might be due to very long running queries. Check your queries as well.
Make sure:
<prop key="hibernate.c3p0.checkoutTimeout">30</prop>
has an enough connection acquire timeout value.
I have a problem with hibernate query.
UPDATE:
When I use this query it works like a charm:
public static List<Korisnik> UzmiSveKorisnike()
{
EntityManager em = Konekcija.getEmf().createEntityManager();
TypedQuery<Korisnik> q = em.createQuery("select k from Korisnik k where k.isActive = 1", Korisnik.class);
List<Korisnik> resultList = q.getResultList();
em.close();
return resultList;
}
But when I use one listed below, to select single result (like for login)...
I get this error: WARN: SQL Error: 1064, SQLState: 42000
I have tried variety of ways to implement this query, but without success. I will list them at the end of the post.
This is the code:
public static Korisnik ProvjeraKorisnickihPodataka(String kIme, String kLozinka)
{
EntityManager em = Konekcija.getEmf().createEntityManager();
{
TypedQuery<Korisnik> q = em.createQuery("select k from Korisnik k where k.isActive = 1 AND k.korisnickoIme=:ime AND k.lozinka =:lozinka", Korisnik.class);
q.setParameter("ime", kIme);
q.setParameter("lozinka", kLozinka);
Korisnik provjeren = q.getSingleResult();
em.close();
return provjeren;
Even if I replace :ime and :lozinka with actual data like "k.korisnickoIme='msbtest' and k.lozinka = 'msbtest'" I get the same error.
Your help is appreciated.
Thank you!
Complete stack:
Hibernate: select TOP(?) korisnik0_.KorisnikID as KorisnikID11_, korisnik0_.agencija_AgencijaID as agencija8_11_, korisnik0_.ime as ime11_, korisnik0_.isActive as isActive11_, korisnik0_.kontakt as kontakt11_, korisnik0_.korisnickoIme as korisnic5_11_, korisnik0_.lozinka as lozinka11_, korisnik0_.prezime as prezime11_, korisnik0_.rola_RolaID as rola9_11_ from Korisnik korisnik0_ where korisnik0_.isActive=1 and korisnik0_.korisnickoIme=? and korisnik0_.lozinka=?
Jul 05, 2013 11:45:22 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1064, SQLState: 42000
Jul 05, 2013 11:45:22 AM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: 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 '.KorisnikID as KorisnikID11_, korisnik0_.agencija_AgencijaID as agencija8_11_, k' at line 1
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: 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 '.KorisnikID as KorisnikID11_, korisnik0_.agencija_AgencijaID as agencija8_11_, k' at line 1
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1377)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1300)
at org.hibernate.ejb.QueryImpl.getSingleResult(QueryImpl.java:318)
at Servis.LoginServis.ProvjeraKorisnickihPodataka(LoginServis.java:35)
at UI.LogInFrm.do_btnPrijava_widgetSelected(LogInFrm.java:173)
at UI.LogInFrm$1.widgetSelected(LogInFrm.java:121)
at org.eclipse.swt.widgets.TypedListener.handleEvent(Unknown Source)
at org.eclipse.swt.widgets.EventTable.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Widget.sendEvent(Unknown Source)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Unknown Source)
at org.eclipse.swt.widgets.Display.readAndDispatch(Unknown Source)
at UI.LogInFrm.main(LogInFrm.java:44)
Caused by: org.hibernate.exception.SQLGrammarException: 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 '.KorisnikID as KorisnikID11_, korisnik0_.agencija_AgencijaID as agencija8_11_, k' at line 1
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:82)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at com.sun.proxy.$Proxy10.executeQuery(Unknown Source)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1926)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1727)
at org.hibernate.loader.Loader.doQuery(Loader.java:852)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:293)
at org.hibernate.loader.Loader.doList(Loader.java:2411)
at org.hibernate.loader.Loader.doList(Loader.java:2397)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2227)
at org.hibernate.loader.Loader.list(Loader.java:2222)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:470)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1247)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
at org.hibernate.ejb.QueryImpl.getSingleResult(QueryImpl.java:285)
... 9 more
Caused by: 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 '.KorisnikID as KorisnikID11_, korisnik0_.agencija_AgencijaID as agencija8_11_, k' at line 1
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1053)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4096)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4028)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2490)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2651)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2734)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2322)
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.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
... 25 more
mapping goes like this:
/**
** Class Korisnik
**/
#Entity
public class Korisnik implements Serializable {
//Fields
#Id
#GeneratedValue
private Integer KorisnikID;
private String ime;
private String prezime;
private String kontakt;
private String korisnickoIme;
private String lozinka;
private Boolean isActive;
#JoinColumn(nullable = false)
#ManyToOne
private Agencija agencija;
#JoinColumn(nullable = false)
#ManyToOne
private Rola rola;
and getters and setters go...
OK, my persistence.xml file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="MojaOznaka1" transaction-type="RESOURCE_LOCAL">
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<!-- Podaci o bazi podataka -->
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://xxxxxxxxx.xxxxxxxxx.xxx/xxxxxxxxx/" />
<property name="javax.persistence.jdbc.user" value="xxxxxx" />
<property name="javax.persistence.jdbc.password" value="xxxxxx" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<!-- hiberante dialect -->
<property name="hibernate.dialect" value="org.hibernate.dialect.SQLServer2008Dialect" />
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size" value="1" />
<!-- Ispis SQL koda u konzolu -->
<property name="hibernate.show_sql" value="true" />
<!-- formatiranje SQL koda ispisanog u konzolni prozor -->
<property name="hibernate.format_sql" value="false" />
<!-- Vrijednost "update" kreira tabele ako nepostoje -->
<!-- <property name="hibernate.hbm2ddl.auto" value="update" /> -->
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class" value="thread" />
<!-- Disable the second-level cache -->
<property name="cache.provider_class" value="org.hibernate.cache.NoCacheProvider" />
<!-- automatsko prepoznavanje JPA klasa -->
<property name="hibernate.archive.autodetection" value="class, hbm" />
</properties>
</persistence-unit>
</persistence>
OK, now what???
The query output you give suggests you told Hibernate to generate SQL for a MS-SQL Server (using TOP(1) to fetch the topmost row).
Since you're using a mysql database as a backend, that won't work. Try adding
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
to your persistence.xml or wherever you configure JPA.
As #Secko mentions in the comment, omitting the dialect altogether might even select a better (more specific) one.
This error usually indicates some mapping error. Are all fields used in the where are actually fields of the "Korisnik" class? HQL uses the field names and not the column names from the database.