Cannot call a method on closed teradata jdbc connection - java

In my spring boot project I am losing sometimes the connection to the teradata database. I would like to know how I can tell spring to close and open the connection again.
I see after several days of runtime exceptions like
Caused by: java.sql.SQLException: [Teradata JDBC Driver] [TeraJDBC 16.10.00.03] [Error 1095] [SQLState HY000] Cannot call a method on closed connection
at com.teradata.jdbc.jdbc_4.util.ErrorFactory.makeDriverJDBCException(ErrorFactory.java:95) ~[terajdbc4-16.10.00.03.jar!/:16.10.00.03]
at com.teradata.jdbc.jdbc_4.util.ErrorFactory.makeDriverJDBCException(ErrorFactory.java:65) ~[terajdbc4-16.10.00.03.jar!/:16.10.00.03]
at com.teradata.jdbc.jdbc_4.TDSession.prepareStatement(TDSession.java:1323) ~[terajdbc4-16.10.00.03.jar!/:16.10.00.03]
at com.teradata.jdbc.jdbc_4.TDSession.prepareStatement(TDSession.java:1375) ~[terajdbc4-16.10.00.03.jar!/:16.10.00.03]
at com.teradata.jdbc.jdbc_4.TDSession.prepareStatement(TDSession.java:1361) ~[terajdbc4-16.10.00.03.jar!/:16.10.00.03]
at sun.reflect.GeneratedMethodAccessor63.invoke(Unknown Source) ~[na:na]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_162]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_162]
at org.apache.tomcat.jdbc.pool.ProxyConnection.invoke(ProxyConnection.java:126) ~[tomcat-jdbc-8.5.20.jar!/:na]
at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108) ~[tomcat-jdbc-8.5.20.jar!/:na]
at org.apache.tomcat.jdbc.pool.interceptor.AbstractCreateStatementInterceptor.invoke(AbstractCreateStatementInterceptor.java:75) ~[tomcat-jdbc-8.5.20.jar!/:na]
at org.apache.tomcat.jdbc.pool.JdbcInterceptor.invoke(JdbcInterceptor.java:108) ~[tomcat-jdbc-8.5.20.jar!/:na]
at org.apache.tomcat.jdbc.pool.DisposableConnectionFacade.invoke(DisposableConnectionFacade.java:81) ~[tomcat-jdbc-8.5.20.jar!/:na]
at com.sun.proxy.$Proxy73.prepareStatement(Unknown Source) ~[na:na]
at org.springframework.jdbc.core.JdbcTemplate$SimplePreparedStatementCreator.createPreparedStatement(JdbcTemplate.java:1521) ~[spring-jdbc-4.3.11.RELEASE.jar!/:4.3.11.RELEASE]
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:627) ~[spring-jdbc-4.3.11.RELEASE.jar!/:4.3.11.RELEASE]
... 25 common frames omitted
When trying to access the database.
I am using an autowired JdbcTemplate when accessing the database. I can catch the exception, but I do not know how to tell spring to kill and reconnect to the database.
I am using the following dependencies.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.teradata.jdbc</groupId>
<artifactId>terajdbc4</artifactId>
<version>16.10.00.03</version>
</dependency>
<dependency>
<groupId>com.teradata.jdbc</groupId>
<artifactId>tdgssconfig</artifactId>
<version>16.10.00.03</version>
</dependency>
After searching stackoverflow, I found examples how to add reconnection configs for different databases, but not for teradata. Can I use similar configs?
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.7.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>

java.sql.Connection conn;
java.sql.Statement stmt;
try {
stmt = conn.createStatement();
stmt.executeQuery("SELECT USER");
} catch (SQLException e) {
// ... open connection here
}

Related

Is Hibernate supposed to be difficult to set up? I keep running into unsolvable errors

I am trying to set up Hibernate in my project to enable ORM-based storage in my database.
Right now I am simply trying to load a configuration in Hibernate to open a session. I figured that this would be an easy test to see if everything worked, after which I could start on the more daunting tasks of actually mapping my classes.
But I didn't realise that just getting to load Hibernate would already be a process that I'd get stuck on for over a day.
Yesterday I couldn't get past an issue with loading the .cfg.xml files. I would continously run into this error:
[15:40:41 ERROR]: [org.bukkit.craftbukkit.v1_19_R1.CraftServer] Unable to perform unmarshalling at line number 0 and column 0 in RESOURCE test.cfg.xml. Message: null initializing LiberCore v0.3 (Is it up to date?)
org.hibernate.internal.util.config.ConfigurationException: Unable to perform unmarshalling at line number 0 and column 0 in RESOURCE test.cfg.xml. Message: null
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:134) ~[?:?]
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:66) ~[?:?]
at org.hibernate.boot.cfgxml.internal.ConfigLoader.loadConfigXmlResource(ConfigLoader.java:57) ~[?:?]
at org.hibernate.boot.registry.StandardServiceRegistryBuilder.configure(StandardServiceRegistryBuilder.java:254) ~[?:?]
at org.hibernate.cfg.Configuration.configure(Configuration.java:260) ~[?:?]
at net.libercraft.data.database.HibernateManager.<init>(HibernateManager.java:29) ~[?:?]
at net.libercraft.data.DataManager.initializeDatabase(DataManager.java:17) ~[?:?]
at net.libercraft.main.Main.onLoad(Main.java:34) ~[?:?]
at org.bukkit.craftbukkit.v1_19_R1.CraftServer.loadPlugins(CraftServer.java:460) ~[purpur-1.19.2.jar:git-Purpur-1765]
at net.minecraft.server.dedicated.DedicatedServer.e(DedicatedServer.java:314) ~[purpur-1.19.2.jar:git-Purpur-1765]
at net.minecraft.server.MinecraftServer.v(MinecraftServer.java:1142) ~[purpur-1.19.2.jar:git-Purpur-1765]
at net.minecraft.server.MinecraftServer.lambda$spin$1(MinecraftServer.java:310) ~[purpur-1.19.2.jar:git-Purpur-1765]
at java.lang.Thread.run(Thread.java:833) [?:?]
Caused by: javax.xml.bind.JAXBException: Implementation of JAXB-API has not been found on module path or classpath.
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:278) ~[?:?]
at javax.xml.bind.ContextFinder.find(ContextFinder.java:421) ~[?:?]
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721) ~[?:?]
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662) ~[?:?]
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:123) ~[?:?]
... 12 more
Caused by: java.lang.ClassNotFoundException: com.sun.xml.internal.bind.v2.ContextFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:445) ~[?:?]
at java.lang.ClassLoader.loadClass(ClassLoader.java:587) ~[?:?]
at java.lang.ClassLoader.loadClass(ClassLoader.java:520) ~[?:?]
at javax.xml.bind.ServiceLoaderUtil.nullSafeLoadClass(ServiceLoaderUtil.java:122) ~[?:?]
at javax.xml.bind.ServiceLoaderUtil.safeLoadClass(ServiceLoaderUtil.java:155) ~[?:?]
at javax.xml.bind.ContextFinder.newInstance(ContextFinder.java:276) ~[?:?]
at javax.xml.bind.ContextFinder.find(ContextFinder.java:421) ~[?:?]
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:721) ~[?:?]
at javax.xml.bind.JAXBContext.newInstance(JAXBContext.java:662) ~[?:?]
at org.hibernate.boot.cfgxml.internal.JaxbCfgProcessor.unmarshal(JaxbCfgProcessor.java:123) ~[?:?]
... 12 more
Googling + reading other posts first just pointed me to a bunch of libraries to add because JAXB was no longer included with java by default. So I tried adding the following (different posts pointed to different libraries which made it pretty confusing..):
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>javax.transaction-api</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>javax.activation</groupId>
<artifactId>javax.activation-api</artifactId>
<version>1.2.0</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.1-api</artifactId>
<version>1.0.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.common</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>6.0.4.Final</version>
</dependency>
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-core</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.25.0-GA</version>
</dependency>
This didn't change much as I just kept getting the same error.
After a bit of googling, I found something that explained about a jaxb.properties file that I could use to change the package pointing to com.sun.xml.internal.bind.v2.ContextFactory to a package that should be included. This worked for some time, at which point I just got errors that it couldn't find my cfg.xml files. When I tried placing those at a different location in my .jar, I went back to the error above however.
I also read about using a hibernate.properties file instead of using xml. However, I want to include different config files in my jar and select one based on the environment that my application is running in. For that reason I don't want to try just a simple hibernate.properties file, since that won't really allow me to customize it.
Today I decided to take a different route. Instead of providing the configuration via the xml file, I would just enter the configuration programmatically. This has solved the previous error of not being able to process the xml files.
But now I am getting new errors that I am unable to solve.
[09:22:53 ERROR]: [org.bukkit.craftbukkit.v1_19_R1.CraftServer] com/fasterxml/classmate/TypeResolver initializing LiberCore v0.3 (Is it up to date?)
java.lang.NoClassDefFoundError: com/fasterxml/classmate/TypeResolver
at org.hibernate.boot.internal.ClassmateContext.<init>(ClassmateContext.java:16) ~[?:?]
at org.hibernate.boot.internal.BootstrapContextImpl.<init>(BootstrapContextImpl.java:81) ~[?:?]
at org.hibernate.boot.internal.MetadataBuilderImpl.<init>(MetadataBuilderImpl.java:124) ~[?:?]
at org.hibernate.boot.MetadataSources.getMetadataBuilder(MetadataSources.java:158) ~[?:?]
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:673) ~[?:?]
at net.libercraft.data.database.HibernateManager.<init>(HibernateManager.java:50) ~[?:?]
at net.libercraft.data.DataManager.initializeDatabase(DataManager.java:17) ~[?:?]
at net.libercraft.main.Main.onLoad(Main.java:34) ~[?:?]
at org.bukkit.craftbukkit.v1_19_R1.CraftServer.loadPlugins(CraftServer.java:460) ~[purpur-1.19.2.jar:git-Purpur-1765]
at net.minecraft.server.dedicated.DedicatedServer.e(DedicatedServer.java:314) ~[purpur-1.19.2.jar:git-Purpur-1765]
at net.minecraft.server.MinecraftServer.v(MinecraftServer.java:1142) ~[purpur-1.19.2.jar:git-Purpur-1765]
at net.minecraft.server.MinecraftServer.lambda$spin$1(MinecraftServer.java:310) ~[purpur-1.19.2.jar:git-Purpur-1765]
at java.lang.Thread.run(Thread.java:833) [?:?]
Caused by: java.lang.ClassNotFoundException: com.fasterxml.classmate.TypeResolver
at org.bukkit.plugin.java.PluginClassLoader.loadClass0(PluginClassLoader.java:153) ~[purpur-api-1.19.2-R0.1-SNAPSHOT.jar:?]
at org.bukkit.plugin.java.PluginClassLoader.loadClass(PluginClassLoader.java:105) ~[purpur-api-1.19.2-R0.1-SNAPSHOT.jar:?]
at java.lang.ClassLoader.loadClass(ClassLoader.java:520) ~[?:?]
... 13 more
After googling I found a few posts that give some solutions:
How to resolve java.lang.NoClassDefFoundError: com/fasterxml/classmate/TypeResolver while running spring boot app
Caused by: java.lang.ClassNotFoundException: com.fasterxml.jackson.databind.JavaType not found
but these are not much help to me.
I tried adding the hibernate-validator library (multiple versions) but it didn't solve the error. I wouldn't know how I could swap the com.fasterxml.jackson with org.codehaus.jackson packages or even if there are org.codehaus.jackson being used in my project.
I feel like I'm doing something essentially wrong. Because in between these errors that I just can't solve, I am getting a lot more ClassNotFoundException etc. that require me to just import more maven libraries to fix them. Isn't that something that Maven should take care of by itself? Like, shouldn't it automatically load any dependant libraries for the libraries that I add to my pom.xml? Why is it requiring me to add all of those manually before my software will work.
None of the tutorial videos on youtube talk about that process, they simply tell you to add the single maven dependancy for hibernate itself. No extra libraries required. So it seems odd to me that I'm being led in that direction by these errors.
It is quite essential for me to implement an ORM solution to my project, and I'm bummed out it's going this way for me. I heard Hibernate was the best solution for this, but maybe there's different solutions for me to try out?
For some context: I'm working on a plugin for the game minecraft and the database will be used to store data about players and other game features.
Bear in mind that if you are on a recent platform 'javax' libraries may have moved to the package 'jakarta'. Try searching in your IDE/classpath what the actual implementations are! I have been successful with this.
<dependency>
<groupId>jakarta.activation</groupId>
<artifactId>javax.activation-api</artifactId>
<version>2.0.1</version>
</dependency>
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>4.0.0</version>
</dependency>

Not able to connect spring jpa with Oracle

Hi I am using below configuration still I am getting error.
spring.datasource.url=jdbc:oracle:thin#sca00tof.us.dell.com:1521:mfg1229
spring.datasource.username=apps
spring.datasource.password=xxxx
spring.datasource.driver-class=oracle.jdbc.driver.OracleDriver
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=Oracle12cDialect
below dependency i used in pom.xml
<dependency>
<groupId>com.oracle.database.jdbc</groupId>
<artifactId>ojdbc8</artifactId>
<scope>runtime</scope>
</dependency>
still I am getting below error.
Caused by: java.lang.ClassNotFoundException: Could not load requested class : Oracle12cDialect
at org.hibernate.boot.registry.classloading.internal.AggregatedClassLoader.findClass(AggregatedClassLoader.java:210) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:589) ~[na:na]
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522) ~[na:na]
at java.base/java.lang.Class.forName0(Native Method) ~[na:na]
at java.base/java.lang.Clas?s.forName(Class.java:427) ~[na:na]
enter code here
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:130) ~[hibernate-core-5.4.23.Final.jar:5.4.23.Final]
... 28 common frames omitted
WHat is the problem in my configuration. instead of driver-class i also checked with driver-class-name
I checked OracleDialect, Oracle10gDialect and Oracle12cDialect . for all the 3 i am getting same error.
there is nothing like "Oracle12cDialect" dialect. you need to write in proper way. :--
in your property file it is:
spring.jpa.properties.hibernate.dialect=Oracle12cDialect
spring.datasource.driver-class=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin#sca00tof.us.dell.com:1521:mfg1229
but it should be:--
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle12cDialect
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin#//sca00tof.us.dell.com:1521/mfg1229
if does not work then please change to:
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.Oracle10gDialect
The dialect for Oracle12c can be use with hibernate 5.x.
You should add this to your classpath:
<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.24.Final</version>
</dependency>
Please note that you need the dialect for the coreesponding Version of Oracle DB.
How ever I can't see the exact framework you are using. Please check that the obove dependency is part of your classpath. This may come with other dependencies such as JPA oder spring-data.
Also please note that your jdbc string seems to be wrong.
It should look like this:
url="jdbc:oracle:thin:#sca00tof.us.dell.com:1521:mfg1229"
See here for details: URL string format for connecting to Oracle database with JDBC

SingletonEhCacheRegionFactory is no longer available when upgrading from Hibernate 5.2 to 5.3

A project I work on is currently using Hibernate version 5.2.15.Final. When configuring the second-level cache, the project has been using org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory as the value for hibernate.cache.region.factory_class.
When I change the Hibernate version to 5.3.12.Final, SingletonEhCacheRegionFactory is no longer in that package. A class with that same name is available in the net.sf.ehcache.hibernate package, and I can use that with no compilation errors. But if I run it I get an error when it tries to build a session:
org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.cache.spi.RegionFactory]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.boot.internal.MetadataBuilderImpl$MetadataBuildingOptionsImpl.<init>(MetadataBuilderImpl.java:688)
at org.hibernate.boot.internal.MetadataBuilderImpl.<init>(MetadataBuilderImpl.java:123)
at org.hibernate.boot.internal.MetadataBuilderImpl.<init>(MetadataBuilderImpl.java:93)
If I dig deeper into the stack trace, the real error seems to be this:
Caused by: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory] as strategy [org.hibernate.cache.spi.RegionFactory]
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:133)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveStrategy(StrategySelectorImpl.java:212)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.resolveStrategy(StrategySelectorImpl.java:169)
at org.hibernate.cache.internal.RegionFactoryInitiator.resolveRegionFactory(RegionFactoryInitiator.java:93)
at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:47)
at org.hibernate.cache.internal.RegionFactoryInitiator.initiateService(RegionFactoryInitiator.java:32)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:94)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
... 64 more
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [net.sf.ehcache.hibernate.SingletonEhCacheRegionFactory]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:137)
at org.hibernate.boot.registry.selector.internal.StrategySelectorImpl.selectStrategyImplementor(StrategySelectorImpl.java:129)
... 71 more
Caused by: java.lang.NoClassDefFoundError: org/hibernate/cache/QueryResultsRegion
at java.base/java.lang.Class.forName0(Native Method)
at java.base/java.lang.Class.forName(Class.java:374)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:131)
... 72 more
Caused by: java.lang.ClassNotFoundException: org.hibernate.cache.QueryResultsRegion
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
... 75 more
Here's what my pom.xml dependencies look like:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.12.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-ehcache</artifactId>
<version>5.3.12.Final</version>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache-core</artifactId>
<version>2.6.11</version>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>5.3.12.Final</version>
</dependency>
Okay, I think I figured out the problem. Previously my code had been fetching the full class name and path by doing:
SingletonEhCacheRegionFactory.class.getCanonicalName()
But in Hibernate 5.3 the class had been moved to an internal package, which is why I could no longer find it. If I used a hardcoded string with the old package name ("org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory"), I no longer get that exception.

How to setup Spring JDBC Connection Pooling with Spring Boot?

Am using Spring Boot 1.5.4 with Spring JDBC.
Have a Spring Boot Microservice which uses Spring JDBC has the following issue when trying to conduct an HTTP PUT (after a bunch of users try conducting an HTTP PUT) which trickles to this Spring JDBC call:
2018-10-10 19:40:02 [http-nio-8081-exec-4] ERROR c.v.r.RepositoryImpl - Problem in updateData() method:
"org.springframework.dao.DataAccessResourceFailureException: PreparedStatementCallback; SQL [select a.user_id,b.user_id, from user a join user_profile b where a.user_id=b.user_id and a.date=?;]; No operations allowed after connection closed.; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
at org.springframework.jdbc.support.SQLExceptionSubclassTranslator.doTranslate(SQLExceptionSubclassTranslator.java:79)
at java.lang.Thread.run(Thread.java:748)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed.
at com.mysql.jdbc.Util.handleNewInstance(Util.java:377)
at com.mysql.jdbc.Util.getInstance(Util.java:360)
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 28,915,589 milliseconds ago. The last packet sent successfully to the server was 9 milliseconds ago.
at com.myapp.repository.RepositoryImpl.updateData(RepositoryImpl.java:74)
at com.myapp.repository.RepositoryImpl$$FastClassBySpringCGLIB$$1be9dd8e.invoke(<generated>)
... 52 common frames omitted
Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2914)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3337)
... 83 common frames omitted
pom.xml:
<artifactId>MyService</artifactId>
<packaging>jar</packaging>
<version>1.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
</parent>
<properties>
<java.version>1.7</java.version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.33</version>
</dependency>
</dependencies>
Am guessing that I need to setup a JDBC connection pool...
Inside my application.properties settings, (I have two different databases - one local and one remote, its losing connection with the remote database; database2):
# Local
spring.datasource.database1.url=jdbc:mysql://localhost/database1?zeroDateTimeBehavior=convertToNull
spring.datasource.database1.username=root
spring.datasource.database1.password=ret2my
spring.datasource.database1.driverClassName=com.mysql.jdbc.Driver
# Remote
spring.datasource.database2.url=jdbc:mysql://read-replica-database-production.cranmichpmc.us-west-2.rds.amazonaws.com/database2?zeroDateTimeBehavior=convertToNull
spring.datasource.database2.username=root
spring.datasource.database2.password=ret2a$$
spring.datasource.database2.driverClassName=com.mysql.jdbc.Driver
Should I add this for the second database:
spring.datasource.database2.hikari.maximum-pool-size=10
spring.datasource.database2.hikari.connection-timeout=60000
Are there other useful params that I should consider?
spring.datasource.url=jdbc:mysql://10.168.143.140:3306/database_name
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.hikari.maximum-pool-size=4
more detailed information can be found at :
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html

Why I can't retrieve a database field havin “point” as data type using Hibernate5\Spring Data JPA into this Spring Boot project?

I am working on a Spring Boot application using Hibernate 5 to work on a PostgreSQL database (but this is not so important, I have the same problem trying to do the same operation on MySQL). The project use also Spring Data JPA on Hibernate 5.
So I am having trouble configuring the Hibernate Spatial GIS feature natively provided by Hibernate 5.
I have the following simple database table named cities:
Field Type
----------------------------------------------------------------
id bigint (it is the PK)
name character varying
location point (it contains the coordinates)
So for example this table contains this record:
id name locoation
--------------------------------------
1 San Francisco (-194,53)
Ok, now I have configured Spring Boot to use Hibernate 5 and JPA to retrieve information from my database. It works fine untill when I have to retrieve the value into the point field (I have try on other table that don't use the spatial feature and it works perfectly fine).
So I have done in this way.
I have this Cities entity class that map the previous cities database table:
import com.vividsolutions.jts.geom.Point;
import javax.persistence.*;
#Entity
#Table(name = "cities")
public class Cities {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
private String name;
#Column(name = "location", columnDefinition="Point")
private Point location;
}
I am using this implementation of the Point class: com.vividsolutions.jts.geom.Point because I found it on some tutorial but I am not sure if it is correct because I also can chose these other implementations:
org.geolatte.geom.Point
org.springframework.data.geo.Point
I have tryied also with these other implementation of the Point class but I still have the same error that I am going to describe.
Then I have this Spring Data JPA interface that represent my DAO class:
#Repository
public interface CitiesDAO extends JpaRepository<Cities, Long> {
Cities findById(#Param("id") Long id);
}
As you can see it extends JpaRepository and the method signature "implements" my query (using JPA).
So, into my JUnit test class I implemented this test method:
#Test
public void testCitiesDAO() {
System.out.println("testCitiesDAO() START");
Cities city = citiesDAO.findById(1L);
System.out.println("testCitiesDAO() END");
}
The problem is that performing this test method (that should retrieve the record into the cities table), when the findById(1L) method is performed, I obtain this deserialization error on my field having point as data type:
Hibernate: select cities0_.id as id1_0_, cities0_.location as location2_0_, cities0_.name as name3_0_ from cities cities0_ where cities0_.id=?
org.springframework.orm.jpa.JpaSystemException: could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:333)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:491)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy104.findById(Unknown Source)
at com.betriuvis.controller.test.PlaceSearcherControllerTest.testCitiesDAO(PlaceSearcherControllerTest.java:88)
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 org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
Caused by: org.hibernate.type.SerializationException: could not deserialize
at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:243)
at org.hibernate.internal.util.SerializationHelper.deserialize(SerializationHelper.java:287)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.fromBytes(SerializableTypeDescriptor.java:138)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:113)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:27)
at org.hibernate.type.descriptor.sql.VarbinaryTypeDescriptor$2.doExtract(VarbinaryTypeDescriptor.java:60)
at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:238)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:234)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:224)
at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:300)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2738)
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1729)
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1655)
at org.hibernate.loader.Loader.getRow(Loader.java:1544)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:727)
at org.hibernate.loader.Loader.processResultSet(Loader.java:972)
at org.hibernate.loader.Loader.doQuery(Loader.java:930)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
at org.hibernate.loader.Loader.doList(Loader.java:2617)
at org.hibernate.loader.Loader.doList(Loader.java:2600)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2429)
at org.hibernate.loader.Loader.list(Loader.java:2424)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1326)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87)
at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606)
at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:529)
at org.hibernate.jpa.criteria.compile.CriteriaQueryTypeQueryAdapter.getSingleResult(CriteriaQueryTypeQueryAdapter.java:54)
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 org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:372)
at com.sun.proxy.$Proxy111.getSingleResult(Unknown Source)
at org.springframework.data.jpa.repository.query.JpaQueryExecution$SingleEntityExecution.doExecute(JpaQueryExecution.java:210)
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:82)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:114)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:104)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:482)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
... 36 more
Caused by: java.io.StreamCorruptedException: invalid stream header: 282D3139
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:806)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:309)
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:299)
at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:218)
... 86 more
So, Hibernate generate and perform this query:
select cities0_.id as id1_0_, cities0_.location as location2_0_, cities0_.name as name3_0_ from cities cities0_ where cities0_.id = 1
that performed directly as SQL code works fine. This is not a query problem but a mapping problem on the entity class or a configuration problem of Hibernate\JPA on Spring Boot settings.
Reading online it seems to me that this kind of excepetion could depend by the fact that Hibernate can't put the retrieved data into the field having type point (I have tried with a simplified version of the same table that doesn't have the point field and the mapping works fine and correctly retrieve data).
So, this is my application.properties file content (that is the only configuration file that I have on my project):
#No auth protected
endpoints.shutdown.sensitive=true
#Enable shutdown endpoint
endpoints.shutdown.enabled=true
logging.file=BeTriviusController.log
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR
# Thymeleaf
spring.thymeleaf.cache:false
# DATABASE CONFIG ----------------------------------------------------------------------------------------------------
spring.datasource.url = jdbc:postgresql://localhost:5432/test1
spring.datasource.username = postgres
spring.datasource.password = Bl4tte_Te4m
spring.datasource.driver-class-name = org.postgresql.Driver
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate5.SpringSessionContext
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update, validate)
spring.jpa.hibernate.ddl-auto = validate
#spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.database-platform=org.hibernate.spatial.dialect.postgis.PostgisDialect
The datasource settings are correctly setted. The standard Hibernate and JPA settings I think that are correct (infact using it on table that not involve Hibernate Spatial feature I have not problem).
I have these 2 settings:
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.database-platform=org.hibernate.spatial.dialect.postgis.PostgisDialect
The first one should be simply related to the dialect that jpa have to use. The econd one I think that is needed to specify that I have to use the Hibernate Spatial dialect for PostgreSQL database. But on this last configuration I am not so sure.
I also put here my pom.xml file, maybe I have some wrong dependency:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>BeTriviusController</groupId>
<artifactId>BeTriviusController</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<springboot.version>1.4.1.RELEASE</springboot.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-spatial</artifactId>
<version>5.0.1.Final</version>
<!--<version>4.0</version>-->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
I have no idea about how to solve it: is it a configuration problem (maybe Spring Boot is using a wrong version of Hibernate or a wrong dialect setting or something like this?), is it a mapping problem or what?
How can I solve this issue?

Categories

Resources