Hikari connection pool issue with sybase - spring

I have a java spring boot application which does bulk insert data to sybase using Spring JDBC driver . I am using Sybase JDBC driver and uses DriverManagerDataSource and HikariConnectionPool to do the bulk insert. The Datasource creation goes fine and but when i try to creat the HikariConnectionPool its giving error Connection Closed error. Below is the code .As you see i am doing an explicit call to see if connecton is closed and it returns false. I am not ble to understand what i am missing here. TIA for any suggestions.
SOURCE CODE
#Configuration
#Profile("local")
public class SpringJDBCLocalConfiguration {
Logger logger = LoggerFactory.getLogger(SpringJDBCLocalConfiguration.class);
#Bean(name = "dataSource")
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource(){{
setDriverClassName("com.sybase.jdbc4.jdbc.SybDriver");
setUrl("url");
setUsername("username");
setPassword("passwd");
}};;
try {
Connection conn = dataSource.getConnection();
logger.info("SpringJDBCLocalConfiguration conn "+conn);
logger.info("SpringJDBCLocalConfiguration conn isClosed "+conn.isClosed());
}
catch(Exception exc){
logger.error("SpringJDBCLocalConfiguration error getting connection in SpringJDBCLocalConfiguration "+exc);
}
HikariConfig config = new HikariConfig() {{
setDataSource(dataSource);
setConnectionTestQuery("SELECT 1");
}};
HikariDataSource hikariDataSource = new HikariDataSource(config);
return hikariDataSource;
}
#Bean
public JdbcTemplate jdbcTemplate(#Qualifier("dataSource") DataSource dataSource) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource());
return jdbcTemplate;
}
}
ERROR STACK TRACE
[ main] c.j.a.w.e.d.SpringJDBCLocalConfiguration : inside SpringJDBCLocalConfiguration.dataSource method flushStrategy
[ main] com.zaxxer.hikari.HikariConfig : sybase-pool - idleTimeout is close to or more than maxLifetime, disabling it.
[ main] com.zaxxer.hikari.HikariDataSource : sybase-pool - Starting...
[ main] com.zaxxer.hikari.pool.PoolBase : sybase-pool - Driver does not support get/set network timeout for connections. (com.sybase.jdbc4.jdbc.SybConnection.getNetworkTimeout()I)
[ main] com.zaxxer.hikari.pool.HikariPool : sybase-pool - Exception during pool initialization.
java.sql.SQLException: JZ0C0: Connection is already closed.
at com.sybase.jdbc4.jdbc.ErrorMessage.raiseError(ErrorMessage.java:779) ~[jconn4-7.07-27307.jar!/:na]
at com.sybase.jdbc4.jdbc.SybConnection.checkConnection(SybConnection.java:4010) ~[jconn4-7.07-27307.jar!/:na]
at com.sybase.jdbc4.jdbc.SybStatement.close(SybStatement.java:744) ~[jconn4-7.07-27307.jar!/:na]
at com.sybase.jdbc4.jdbc.SybStatement.close(SybStatement.java:719) ~[jconn4-7.07-27307.jar!/:na]
at com.sybase.jdbc4.jdbc.MdaManager.loadMetaData(MdaManager.java:573) ~[jconn4-7.07-27307.jar!/:na]
at com.sybase.jdbc4.jdbc.MdaManager.<init>(MdaManager.java:188) ~[jconn4-7.07-27307.jar!/:na]
at com.sybase.jdbc4.jdbc.MdaManager.<init>(MdaManager.java:171) ~[jconn4-7.07-27307.jar!/:na]
at com.sybase.jdbc4.jdbc.SybConnection.checkMDA(SybConnection.java:4155) ~[jconn4-7.07-27307.jar!/:na]
at com.sybase.jdbc4.jdbc.SybConnection.getMDA(SybConnection.java:3685) ~[jconn4-7.07-27307.jar!/:na]
at com.sybase.jdbc4.tds.Tds.setOption(Tds.java:1829) ~[jconn4-7.07-27307.jar!/:na]
at com.sybase.jdbc4.jdbc.SybConnection.setReadOnly(SybConnection.java:2586) ~[jconn4-7.07-27307.jar!/:na]
at com.zaxxer.hikari.pool.PoolBase.setupConnection(PoolBase.java:409) ~[HikariCP-2.7.9.jar!/:na]
at com.zaxxer.hikari.pool.PoolBase.newConnection(PoolBase.java:370) ~[HikariCP-2.7.9.jar!/:na]
at com.zaxxer.hikari.pool.PoolBase.newPoolEntry(PoolBase.java:194) ~[HikariCP-2.7.9.jar!/:na]
at com.zaxxer.hikari.pool.HikariPool.createPoolEntry(HikariPool.java:460) [HikariCP-2.7.9.jar!/:na]
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:534) [HikariCP-2.7.9.jar!/:na]
at com.zaxxer.hikari.pool.HikariPool.<init>(HikariPool.java:115) [HikariCP-2.7.9.jar!/:na]
at com.zaxxer.hikari.HikariDataSource.<init>(HikariDataSource.java:81) [HikariCP-2.7.9.jar!/:na]

The issue was application was running in cloud and able to establish the database connection but seems firewall killing the connection so at the time of connection pool creation no active connections were found causing this error. I tried explicitly whitelisting the ip address and port but still same issue,but the root cause is the firewall blocking connection.

Related

Spring data jdbc - Multiple data source - Not reading data from secondry

Use case: Read data from oracle and load the same into MySQL.
We are using Spring Data JDBC and OJDBC8.
Issue: Always connecting to the primary data source.
**application.properties**
=======================
spring.datasource.mysql.jdbcUrl = jdbc:mysql://localhost:3306/MySQLData?useSSL=false
spring.datasource.mysql.username = root
spring.datasource.mysql.password = root
spring.datasource.mysql.driverClassName = com.mysql.cj.jdbc.Driver
spring.datasource.oracle.jdbcUrl = jdbc:oracle:thin:#localhost:1521/XE
spring.datasource.oracle.username = root
spring.datasource.oracle.password = ea
spring.datasource.oracle.driverClassName = oracle.jdbc.OracleDriver
**MySqlDataSource.java**
=====================
package com.test.datasource;
#Configuration
#EnableJdbcRepositories(transactionManagerRef = "mysqlJdbcTransactionManager", jdbcOperationsRef = "mysqlJdbcOperationsReference", basePackages = {
"com.test.data.mysql.repository" })
#EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, JdbcRepositoriesAutoConfiguration.class })
public class MySqlDataSource extends AbstractJdbcConfiguration {
#Bean
#Primary
#Qualifier("mysqlDataSource")
#ConfigurationProperties(prefix = "spring.datasource.mysql")
public DataSource dataSourceMySql() {
return DataSourceBuilder.create().build();
}
#Bean
#Primary
#Qualifier("mysqlJdbcOperationsReference")
public NamedParameterJdbcOperations mysqlJdbcOperationsReference(
#Qualifier("mysqlDataSource") DataSource dataSource) {
return new NamedParameterJdbcTemplate(dataSource);
}
#Bean
#Primary
#Qualifier("mysqlJdbcTransactionManager")
public PlatformTransactionManager mysqlJdbcTransactionManager(#Qualifier("mysqlDataSource") final DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
**OracleDataSource.java**
======================
package com.test.datasource;
#Configuration
#EnableTransactionManagement
#EnableJdbcRepositories(transactionManagerRef = "oracleJdbcTransactionManager", jdbcOperationsRef = "oracleJdbcOperationsReference", basePackages = {
"com.test.data.oracle.repository" })
#EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class, JdbcRepositoriesAutoConfiguration.class })
public class OracleDataSource extends AbstractJdbcConfiguration {
#Bean
#Qualifier("oracleDataSource")
#ConfigurationProperties(prefix = "spring.datasource.oracle")
public DataSource dataSourceOracle() {
return DataSourceBuilder.create().build();
}
#Bean
#Qualifier("oracleJdbcOperationsReference")
public NamedParameterJdbcOperations oracleJdbcOperationsReference(
#Qualifier("oracleDataSource") DataSource dataSource) {
return new NamedParameterJdbcTemplate(dataSource);
}
#Bean
#Qualifier("oracleJdbcTransactionManager")
public PlatformTransactionManager oracleJdbcTransactionManager(
#Qualifier("oracleDataSource") final DataSource dataSource) {
return new DataSourceTransactionManager(dataSource);
}
}
package com.test.data.oracle.repository;
#Repository
public interface ServiceRepository extends CrudRepository<Service, Integer> {
}
**Controller.java**
====================
package com.test.controller;
#RestController
#RequestMapping(value = "/api/v1/bnService")
#Api(tags = { "Business Unit operations" })
public class BNServiceController {
#Autowired
private ServiceRepository attributeGroupRepository;
#RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public SuccessVO retrieveConnectorInfoByCode() {
Optional<Service> pagedOtAttributeGroup = attributeGroupRepository.findById(52);
return null;
}
}
**Logs**
========
Adding transactional method 'org.springframework.data.jdbc.repository.support.SimpleJdbcRepository.findById' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly
Returning cached instance of singleton bean 'oracleJdbcTransactionManager'
Creating new transaction with name [org.springframework.data.jdbc.repository.support.SimpleJdbcRepository.findById]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly
HikariPool-2 - configuration:
allowPoolSuspension.............false
autoCommit......................true
catalog.........................none
connectionInitSql...............none
connectionTestQuery.............none
connectionTimeout...............30000
dataSource......................none
dataSourceClassName.............none
dataSourceJNDI..................none
dataSourceProperties............{password=<masked>}
driverClassName................."oracle.jdbc.OracleDriver"
exceptionOverrideClassName......none
healthCheckProperties...........{}
healthCheckRegistry.............none
idleTimeout.....................600000
initializationFailTimeout.......1
isolateInternalQueries..........false
jdbcUrl.........................jdbc:oracle:thin:#localhost:1521/XE
leakDetectionThreshold..........0
maxLifetime.....................1800000
maximumPoolSize.................10
metricRegistry..................none
metricsTrackerFactory...........none
minimumIdle.....................10
password........................<masked>
poolName........................"HikariPool-2"
readOnly........................false
registerMbeans..................false
scheduledExecutor...............none
schema..........................none
threadFactory...................internal
transactionIsolation............default
username........................"ea"
validationTimeout...............5000
HikariPool-2 - Starting...
HikariPool-2 - Added connection oracle.jdbc.driver.T4CConnection#1bfa059c
HikariPool-2 - Start completed.
Acquired Connection [HikariProxyConnection#2136532594 wrapping oracle.jdbc.driver.T4CConnection#1bfa059c] for JDBC transaction
Setting JDBC Connection [HikariProxyConnection#2136532594 wrapping oracle.jdbc.driver.T4CConnection#1bfa059c] read-only
Switching JDBC Connection [HikariProxyConnection#2136532594 wrapping oracle.jdbc.driver.T4CConnection#1bfa059c] to manual commit
Bound value [org.springframework.jdbc.datasource.ConnectionHolder#55db8827] for key [HikariDataSource (HikariPool-2)] to thread [http-nio-8081-exec-2]
Initializing transaction synchronization
Getting transaction for [org.springframework.data.jdbc.repository.support.SimpleJdbcRepository.findById]
Executing prepared SQL query
Fetching JDBC Connection from DataSource
Bound value [org.springframework.jdbc.datasource.ConnectionHolder#400a4f] for key [HikariDataSource (HikariPool-1)] to thread [http-nio-8081-exec-2]
Setting SQL statement parameter value: column index 1, parameter value [52], value class [java.lang.Integer], SQL type 4
Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder#400a4f] for key [HikariDataSource (HikariPool-1)] bound to thread [http-nio-8081-exec-2]
Retrieved value [org.springframework.jdbc.datasource.ConnectionHolder#400a4f] for key [HikariDataSource (HikariPool-1)] bound to thread [http-nio-8081-exec-2]
Loading XML bean definitions from class path resource [org/springframework/jdbc/support/sql-error-codes.xml]
HikariPool-2 - Pool stats (total=1, active=1, idle=0, waiting=0)
Using JAXP provider [com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl]
Trying to resolve XML entity with public ID [-//SPRING//DTD BEAN 2.0//EN] and system ID [https://www.springframework.org/dtd/spring-beans-2.0.dtd]
Trying to locate [spring-beans.dtd] in Spring jar on classpath
Found beans DTD [https://www.springframework.org/dtd/spring-beans-2.0.dtd] in classpath: spring-beans.dtd
Alias definition 'Db2' registered for name 'DB2'
Alias definition 'Hana' registered for name 'HDB'
Alias definition 'Hsql' registered for name 'HSQL'
Alias definition 'SqlServer' registered for name 'MS-SQL'
Alias definition 'Postgres' registered for name 'PostgreSQL'
Loaded 11 bean definitions from class path resource [org/springframework/jdbc/support/sql-error-codes.xml]
Caching SQL error codes for DataSource [com.zaxxer.hikari.HikariDataSource#3b332962]: database product name is 'MySQL'
Translating SQLException with SQL state '42S02', error code '1146', message [Table 'MySQLData.service' doesn't exist]; SQL was [SELECT `service`.`SERVICE_ID` AS `SERVICE_ID`, `service`.`SERVICE_NAME` AS `SERVICE_NAME` FROM `service` WHERE `service`.`SERVICE_ID` = ?] for task [PreparedStatementCallback]
Completing transaction for **[org.springframework.data.jdbc.repository.support.SimpleJdbcRepository.findById] after exception: org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; bad SQL grammar [SELECT `service`.`SERVICE_ID` AS `SERVICE_ID`, `service`.`SERVICE_NAME` AS `SERVICE_NAME` FROM `service` WHERE `service`.`SERVICE_ID` = ?]; nested exception is java.sql.SQLSyntaxErrorException: Table 'MySQLData.service' doesn't exist**
Based on the logs, I understood that it is loading the oracle driver and due to some issue it couldn't retrieve the data and switching the connection back to MySQL. As MySQL doesn't have those tables it is throwing the exception.
Note:
If I change oracle as primary it is working as expected.
Modified IdentifierProcessing to generalize the SQL generated

Tomcat Restart required after war file deployment for database connection

While deploying a war file (Spring Boot App) on external Tomcat server, I am getting the exception:
com.zaxxer.hikari.HikariConfig - HikariPool-5 - dataSource or dataSourceClassName or jdbcUrl is required
It gets resolved after server restart and application gets started.
Edit:
Datasource configuration is done as follows:
#Bean(name = "datasource")
#ConfigurationProperties(prefix = "app.datasource")
public DataSource appDataSource() {
return DataSourceBuilder.create().build();
}
Properties used:
app.datasource.jdbc-url
app.datasource.username
app.datasource.password
app.datasource.driverClassName
Not getting the reason for this behavior

Connect to remote jms queue with Spring Boot

I'm trying to connect a remote JBOSS, JBOSS EAP 7, JMS queue with spring boot.
Below my code, I have only a configuration class and consumer class.
I see through logs that I'm connecting to localhost, but... WHY???
#Configuration
#EnableJms
public class ActiveMqConnectionFactoryConfig {
String queueName= "JMSTestQueueName";
private static final String INITIAL_CONTEXT_FACTORY = "org.jboss.naming.remote.client.InitialContextFactory";
private static final String CONNECTION_FACTORY = "jms/RemoteConnectionFactory";
public ConnectionFactory connectionFactory() {
try {
System.out.println("Retrieving JMS queue with JNDI name: " + CONNECTION_FACTORY);
JndiObjectFactoryBean jndiObjectFactoryBean = new JndiObjectFactoryBean();
jndiObjectFactoryBean.setJndiName(CONNECTION_FACTORY);
jndiObjectFactoryBean.setJndiEnvironment(getEnvProperties());
jndiObjectFactoryBean.afterPropertiesSet();
return (QueueConnectionFactory) jndiObjectFactoryBean.getObject();
} catch (NamingException e) {
System.out.println("Error while retrieving JMS queue with JNDI name: [" + CONNECTION_FACTORY + "]");
} catch (Exception ex) {
System.out.println("Error error");
ex.getStackTrace();
}
return null;
}
#Bean
Properties getEnvProperties() throws NamingException {
Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, INITIAL_CONTEXT_FACTORY);
env.put(Context.PROVIDER_URL, "http-remoting://<REMOTE_ADDRESS>:8080?broker.persistent=false&broker.useJmx=false");
env.put(Context.SECURITY_PRINCIPAL, <USER>);
env.put(Context.SECURITY_CREDENTIALS, <PASSWORD>);
namingContext = new InitialContext(env);
return env;
}
#Bean
public DefaultJmsListenerContainerFactory jmsListenerContainerFactory(ConnectionFactory connectionFactory) throws NamingException {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
factory.setConnectionFactory(connectionFactory);
factory.setConcurrency("3-10");
JndiDestinationResolver jndiDestinationResolver = new JndiDestinationResolver();
jndiDestinationResolver.setJndiEnvironment(getEnvProperties());
factory.setDestinationResolver(jndiDestinationResolver);
return factory;
}
}
Listener Class:
#Configuration
public class jmsListener {
#JmsListener(destination = "queue/JMSTestQueueName", containerFactory = "jmsListenerContainerFactory")
public void receive(Message message) {
System.out.println("Received Message: " + message);
}
}
The log:
2020-05-27 00:21:58.571 INFO 10368 --- [ main] o.apache.activemq.broker.BrokerService : Apache ActiveMQ 5.15.7 (localhost, ID:ITPC020248-60530-1590531718443-0:1) is starting
2020-05-27 00:21:58.576 INFO 10368 --- [ main] o.apache.activemq.broker.BrokerService : Apache ActiveMQ 5.15.7 (localhost, ID:ITPC020248-60530-1590531718443-0:1) started
2020-05-27 00:21:58.577 INFO 10368 --- [ main] o.apache.activemq.broker.BrokerService : For help or more information please see: http://activemq.apache.org
2020-05-27 00:21:58.617 INFO 10368 --- [ main] o.a.activemq.broker.TransportConnector : Connector vm://localhost started
2020-05-27 00:21:58.659 INFO 10368 --- [ main] jboss.ConsumerClass : Started ConsumerClass in 1.922 seconds (JVM running for 3.504)
Without ?broker.persistent=false&broker.useJmx=false on the JNDI URL I obtain this:
2020-05-27 19:38:34.680 INFO 19752 --- [dpoint" task-13] org.jboss.ejb.client.remoting : EJBCLIENT000016: Channel Channel ID 8f759d73 (outbound) of Remoting connection 336369ee to /172.16.68.80:8080 can no longer process messages
2020-05-27 19:38:37.479 INFO 19752 --- [ main] jboss.ConsumerClass : Started ConsumerClass in 7.194 seconds (JVM running for 9.26)
2020-05-27 19:38:42.772 ERROR 19752 --- [enerContainer-2] o.s.j.l.DefaultMessageListenerContainer : Could not refresh JMS Connection for destination 'queue/JMSTestQueueName' - retrying using FixedBackOff{interval=5000, currentAttempts=0, maxAttempts=unlimited}. Cause: AMQ119031: Unable to validate user
2020-05-27 19:38:48.068 ERROR 19752 --- [enerContainer-2] o.s.j.l.DefaultMessageListenerContainer : Could not refresh JMS Connection for destination 'queue/JMSTestQueueName' - retrying using FixedBackOff{interval=5000, currentAttempts=1, maxAttempts=unlimited}. Cause: AMQ119031: Unable to validate user
2020-05-27 19:38:53.401 ERROR 19752 --- [enerContainer-2] o.s.j.l.DefaultMessageListenerContainer : Could not refresh JMS Connection for destination 'queue/JMSTestQueueName' - retrying using FixedBackOff{interval=5000, currentAttempts=2, maxAttempts=unlimited}. Cause: AMQ119031: Unable to validate user
2020-05-27 19:38:58.699 ERROR 19752 --- [enerContainer-2] o.s.j.l.DefaultMessageListenerContainer : Could not refresh JMS Connection for destination 'queue/JMSTestQueueName' - retrying using FixedBackOff{interval=5000, currentAttempts=3, maxAttempts=unlimited}. Cause: AMQ119031: Unable to validate user
2020-05-27 19:39:04.006 ERROR 19752 --- [enerContainer-2] o.s.j.l.DefaultMessageListenerContainer : Could not refresh JMS Connection for destination 'queue/JMSTestQueueName' - retrying using FixedBackOff{interval=5000, currentAttempts=4, maxAttempts=unlimited}. Cause: AMQ119031: Unable to validate user
2020-05-27 19:39:09.320 ERROR 19752 --- [enerContainer-2] o.s.j.l.DefaultMessageListenerContainer : Could not refresh JMS Connection for destination 'queue/JMSTestQueueName' - retrying using FixedBackOff{interval=5000, currentAttempts=5, maxAttempts=unlimited}. Cause: AMQ119031: Unable to validate user
Your connectionFactory() needs to be a #Bean in order to inject it as an argument into your container factory factory method.
public DefaultJmsListenerContainerFactory jmsListenerContainerFactory(ConnectionFactory connectionFactory) throws NamingException {
Since it's not a #Bean you are getting boot's default connection factory (presumably you have ActiveMQ on the class path).

HibernateException: Use of DefaultSchemaNameResolver requires Dialect to provide the proper SQL statement/command

I am running a spring boot app version 2.1.4.RELEASE. The app is using hibernate 5.4.2.Final and postgresql driver version 42.2.5. Recently i tried to generate the DDL from hibernate in order to see the DDL, and I stumbled upon a error that is bugging me since days.
Using the PostgreSQL 11.2 version (Ubuntu 11.2-1.pgdg18.04+1)
Now when the app is booting it is running into that exception every time.
If i place a break point on the method
org.hibernate.engine.jdbc.env.internal.DefaultSchemaNameResolver.determineAppropriateResolverDelegate(Connection connection)
i see where the exception is occurring i.e. at the point
connection.getSchema();
there are helpful comments in this class
unfortunately Connection#getSchema is only available in Java 1.7 and above
and Hibernate still baselines on 1.6. So for now, use reflection and
leverage the Connection#getSchema method if it is available.
If the JDBC driver does not implement the Java 7 spec, but the JRE is Java 7
then the getSchemaMethod is not null but the call to getSchema() throws an java.lang.AbstractMethodError
well i am running version above 7 i.e. :
java -version
openjdk version "11" 2018-09-25
OpenJDK Runtime Environment 18.9 (build 11+28)
OpenJDK 64-Bit Server VM 18.9 (build 11+28, mixed mode)
I am still running into the following exception on spring boot start i.e. !!!! EVEN BEFOR THE PART OF THE CODE (BEANS) ARE REACHED !!! that are supposed to generate the DDL i.e. the method createSchemaWithHibernate5(LocalSessionFactoryBean sessionFactory).
So that has something to do with the config or the connection type. When i place a breakpoint on then connection type i see it is of type
org.apache.commons.dbcp.PoolableConnection
well that one is extending from "DelegatingConnection" which DOES NOT implement the method getSchema() although it is extending the interface
java.sql.Connection
which does have the method getSchema().
I am not sure how this is supposed to work at all, since none of those are final or abstract classes.
I also see that there is another class called
org.postgresql.jdbc.PgConnection.
How can i force my app to use this one since i see this one indeed DOES implement the method getSchema().
Here is the exception i am running into:
2019-04-17 10:06:42.487 DEBUG tito-pc --- [ restartedMain] .i.f.i.DefaultIdentifierGeneratorFactory : Registering IdentifierGenerator strategy [enhanced-table] -> [org.hibernate.id.enhanced.TableGenerator]
2019-04-17 10:06:43.004 DEBUG tito-pc --- [ restartedMain] o.h.e.j.e.i.JdbcEnvironmentInitiator : Database ->
name : PostgreSQL
version : 11.2 (Ubuntu 11.2-1.pgdg18.04+1)
major : 11
minor : 2
2019-04-17 10:06:43.004 DEBUG tito-pc --- [ restartedMain] o.h.e.j.e.i.JdbcEnvironmentInitiator : Driver ->
name : PostgreSQL JDBC Driver
version : 42.2.5
major : 42
minor : 2
2019-04-17 10:06:43.005 DEBUG tito-pc --- [ restartedMain] o.h.e.j.e.i.JdbcEnvironmentInitiator : JDBC version : 4.2
2019-04-17 10:06:43.023 INFO tito-pc --- [ restartedMain] o.h.d.Dialect : HHH000400: Using dialect: org.hibernate.dialect.PostgreSQL95Dialect
2019-04-17 10:06:43.053 DEBUG tito-pc --- [ restartedMain] o.h.e.j.e.s.IdentifierHelperBuilder : JDBC driver metadata reported database stores quoted identifiers in neither upper, lower nor mixed case
2019-04-17 10:06:54.515 DEBUG tito-pc --- [ restartedMain] o.h.e.j.e.i.DefaultSchemaNameResolver : Unable to use Java 1.7 Connection#getSchema
2019-04-17 10:06:59.058 DEBUG tito-pc --- [ restartedMain] o.h.e.j.e.i.JdbcEnvironmentImpl : Unable to resolve connection default schema
org.hibernate.HibernateException: Use of DefaultSchemaNameResolver requires Dialect to provide the proper SQL statement/command but provided Dialect [org.hibernate.dialect.PostgreSQL95Dialect] did not return anything from Dialect#getCurrentSchemaCommand
at org.hibernate.engine.jdbc.env.internal.DefaultSchemaNameResolver$SchemaNameResolverFallbackDelegate.resolveSchemaName(DefaultSchemaNameResolver.java:100)
at org.hibernate.engine.jdbc.env.internal.DefaultSchemaNameResolver.resolveSchemaName(DefaultSchemaNameResolver.java:76)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.determineCurrentSchemaName(JdbcEnvironmentImpl.java:311)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl.<init>(JdbcEnvironmentImpl.java:266)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:114)
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:175)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:118)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:473)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:84)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:689)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:615)
at org.springframework.orm.hibernate5.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:599)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774)
.....
here is my persistence config:
#Profile("Development")
#Configuration
#EnableTransactionManagement
#Order(value=1)
public class PersistenceConfigDevelopment {
private static Logger logger = LogManager.getLogger(PersistenceConfigDevelopment.class.getName());
#Bean
#Primary
public org.apache.commons.dbcp.BasicDataSource dataSourceReadWrite1() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://localhost:5432/develpmentTestDb");
dataSource.setUsername("admin");
dataSource.setPassword("notABigSecret");
dataSource.setInitialSize(20);
dataSource.setMaxActive(-1);
return dataSource;
}
#Bean
#Primary
public org.springframework.orm.hibernate5.LocalSessionFactoryBean sessionFactory() {
org.springframework.orm.hibernate5.LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setHibernateProperties(hibernateProperties());
sessionFactory.setDataSource(this.dataSourceReadWrite1());
sessionFactory.setPackagesToScan("org.university.");
return sessionFactory;
}
#Bean
public HibernateTransactionManager transactionManager() {
HibernateTransactionManager txManager = new HibernateTransactionManager();
txManager.setSessionFactory(sessionFactory().getObject());
return txManager;
}
#Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
#Bean
public Properties hibernateProperties() {
return new Properties() {
/**
*
*/
private static final long serialVersionUID = 1L;
{
setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL95Dialect");
setProperty("hibernate.chach.provider_class", "org.hibernate.cache.NoCacheProvider");
setProperty("hibernate.show_sql", "true");
setProperty("hibernate.hbm2ddl.auto", "create-drop");
setProperty("hibernate.cache.use_second_level_cache", "false");
setProperty("hibernate.cache.use_query_cache", "false");
// isolation level
setProperty("hibernate.connection.isolation", String.valueOf(Connection.TRANSACTION_SERIALIZABLE));
}
};
}
#Bean
public Boolean createSchemaWithHibernate5(LocalSessionFactoryBean sessionFactory) {
final PostgreSQL95Dialect dialect = new PostgreSQL95Dialect();
StandardServiceRegistry serviceRegistry = sessionFactory.getConfiguration().getStandardServiceRegistryBuilder()
.applySetting("hibernate.dialect", dialect)
.build();
Metadata metadata = new MetadataSources(serviceRegistry).buildMetadata();
new SchemaExport()
.setOutputFile("db-schema.hibernate5.ddl")
.create(EnumSet.of(TargetType.SCRIPT), metadata);
metadata.buildSessionFactory().close();
return Boolean.TRUE;
}
}
Because of this stackoverflow post i tried changing the drivers i.e.
Implementating Method org.postgresql.jdbc4.Jdbc4Connection.getSchema()
and tried using "postgresql" maven artifact instead of "org.postgresql" but that did not helped as well.
Any help is really appreciated.
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<!-- <version>${orgpostgresql.version}</version> -->
</dependency>
<!-- <dependency> -->
<!-- <groupId>postgresql</groupId> -->
<!-- <artifactId>postgresql</artifactId> -->
<!-- <version>${postgresql.version}</version> -->
<!-- </dependency> -->
update 17 April
I was able to get rid of the exception by using another data source i.e. PGSimpleDataSource that also changed the connector to PgConnection, but the DDL is still not being generated. I.e. the file db-schema.hibernate5.ddl is beeing generated but it is empty.
#Bean
#Primary
public PGSimpleDataSource dataSourceReadWrite1() {
PGSimpleDataSource dataSource = new PGSimpleDataSource();
dataSource.setUrl("jdbc:postgresql://localhost:5432/developmentTestDB");
dataSource.setUser("admin");
dataSource.setPassword("notABigSecret");
return dataSource;
}
I struggled with the same problem myself
11:16:07.675 [AWT-EventQueue-0] DEBUG org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator - Database ->
name : PostgreSQL
version : 10.18 (Ubuntu 10.18-0ubuntu0.18.04.1)
major : 10
minor : 18
11:16:07.675 [AWT-EventQueue-0] DEBUG org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator - Driver ->
name : PostgreSQL Native Driver
version : PostgreSQL 9.0 JDBC4 (build 801)
major : 9
minor : 0
11:16:07.675 [AWT-EventQueue-0] DEBUG org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator - JDBC version : 4.0
11:16:07.689 [AWT-EventQueue-0] INFO org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
11:16:07.709 [AWT-EventQueue-0] DEBUG org.hibernate.engine.jdbc.env.spi.IdentifierHelperBuilder - JDBC driver metadata reported database stores quoted identifiers in neither upper, lower nor mixed case
11:16:07.716 [AWT-EventQueue-0] DEBUG org.hibernate.engine.jdbc.env.internal.DefaultSchemaNameResolver - Unable to use Java 1.7 Connection#getSchema
11:16:07.718 [AWT-EventQueue-0] DEBUG org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentImpl - Unable to resolve connection default schema
org.hibernate.HibernateException: Use of DefaultSchemaNameResolver requires Dialect to provide the proper SQL statement/command but provided Dialect [org.hibernate.dialect.PostgreSQLDialect] did not return anything from Dialect#getCurrentSchemaCommand
I had to update the drivers so that it showed
11:45:27.477 [AWT-EventQueue-0] DEBUG org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator - Driver ->
name : PostgreSQL JDBC Driver
version : 42.2.23
major : 42
minor : 2
And I had to change my dialect to
PostgreSQL10Dialect

HikariCP times out when switching from jdk 1.7 to 1.8

In Jenkins switching from env.JAVA_HOME="${tool 'JDK_7u80'}" to javaHome = tool 'JDK_8u74' causes timeout and checkFailFast.
I'm using
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>3.0.0</version>
</dependency>
and
#Bean(destroyMethod = "close")
DataSource dataSource(Environment env) {
HikariConfig dataSourceConfig = new HikariConfig();
dataSourceConfig.setDriverClassName(env.getRequiredProperty("db.driver"));
dataSourceConfig.setJdbcUrl(env.getRequiredProperty("db.url"));
dataSourceConfig.setUsername(env.getRequiredProperty("db.username"));
dataSourceConfig.setPassword(env.getRequiredProperty("db.password"));
System.out.println("Trying to connect to: " + dataSourceConfig.getJdbcUrl());
return new HikariDataSource(dataSourceConfig);
}
2018-04-18 19:44:18, 987 HikariDataSource [INFO] HikariPool-1 - Starting...
.
.
.Caused by: com.zaxxer.hikari.pool.HikariPool$PoolInitializationException: Failed to initialize pool: The TCP/IP connection to the host XXX, port YYY has failed. Error: "Connection timed out: no further information.. Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".
at com.zaxxer.hikari.pool.HikariPool.throwPoolInitializationException(HikariPool.java:576)
at com.zaxxer.hikari.pool.HikariPool.checkFailFast(HikariPool.java:562)
at com.zaxxer.hikari.pool.HikariPool.(HikariPool.java:115)
at com.zaxxer.hikari.HikariDataSource.(HikariDataSource.java:81)
at com.travelport.ep.datastore.springdatajpa.config.SqlServerConfig.dataSource(SqlServerConfig.java:42)

Resources