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

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

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

Hikari connection pool issue with sybase

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.

How can I confirm that Spring Transactions are working properly?

I working on an Spring 3.2 application running in OC4j. I have a number of methods annotated with Spring's #Transactional annotation as follows:
// in MyServiceImpl
#Transactional()
public void insertPaymentData(PaymentParams paymentParams) {
// call to MyDaoImpl which in turn calls a
// Spring JDBC Stored Procedure implementation
}
// in the Stored Procedure implementation
#Transactional(propagation = Propagation.MANDATORY)
public void insertPaymentData(PaymentParams paymentParams) {
// execute procedure here
}
In the logs for my local OC4J instance I see entries such as the following which make me think that Transactions are configured correctly:
[1.2.3.4-user123] 2019-03-20 17:36:14,805 DEBUG AbstractFallbackTransactionAttributeSource::getTransactionAttribute - Adding transactional method 'MyServiceImpl.insertPaymentData' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,timeout_1800; ''
[1.2.3.4-user123] 2019-03-20 17:36:14,809 DEBUG AbstractBeanFactory::doGetBean - Returning cached instance of singleton bean 'transactionManager'
[1.2.3.4-user123] 2019-03-20 17:36:14,812 DEBUG AbstractPlatformTransactionManager::getTransaction - Creating new transaction with name [my.app.service.payments.MyServiceImpl.insertPaymentData]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,timeout_1800; ''
[1.2.3.4-user123] 2019-03-20 17:36:14,821 DEBUG AbstractBeanFactory::doGetBean - Returning cached instance of singleton bean 'transactionManager'
[1.2.3.4-user123] 2019-03-20 17:36:14,822 DEBUG AbstractPlatformTransactionManager::handleExistingTransaction - Participating in existing transaction
[1.2.3.4-user123] 2019-03-20 17:36:14,822 DEBUG DataSourceUtils::doGetConnection - Fetching JDBC Connection from DataSource
[1.2.3.4-user123] 2019-03-20 17:36:14,823 DEBUG DataSourceUtils::doGetConnection - Registering transaction synchronization for JDBC Connection
[1.2.3.4-user123] 2019-03-20 17:38:42,550 DEBUG DataSourceUtils::doReleaseConnection - Returning JDBC Connection to DataSource
[1.2.3.4-user123] 2019-03-20 17:38:42,551 DEBUG AbstractPlatformTransactionManager::processCommit - Initiating transaction commit
Sometimes I see timeout and rollback messages there too.
However when I deploy to the development server provided by the ops department I do not see any messages like this in the logs, although the DEBUG level messages are displayed there too. I added in the following logging lines which I found somewhere on stack overflow:
logger.debug("Transaction name=" + TransactionSynchronizationManager.getCurrentTransactionName());
logger.debug("isActualTransactionActive=" + TransactionSynchronizationManager.isActualTransactionActive());
logger.debug("isSynchronizationActive=" + TransactionSynchronizationManager.isSynchronizationActive());
In the logs I now see things like this:
Transaction name=my.app.service.payments.MyServiceImpl.insertPaymentData
isActualTransactionActive=true
isSynchronizationActive=true
Are these values from TransactionSynchronizationManager telling me anything useful?
Is it telling me that transactions are working fine and to stop worrying?
I have the following in a Spring configuration file:
#Configuration
#EnableTransactionManagement
public class TransactionConfig {
#Bean
public JtaTransactionManager transactionManager() {
return new JtaTransactionManager();
}
}
And I have the following in a spring xml config file:
<tx:annotation-driven transaction-manager="transactionManager" />
Thanks!

Spring boot 2 configure reactive mongo db repository WITHOUT EmbeddedMongo

I am trying to set up a Spring Boot 2 project with Mongo DB but I the problem I am facing is that it keeps spinning up an embedded mongo DB even though I have configured to use external mongo
logs
2018-11-27 18:56:05.725 INFO 73687 --- [ Thread-2] o.s.b.a.mongo.embedded.EmbeddedMongo : note: noprealloc may hurt performance in many applications
2018-11-27 18:56:05.742 INFO 73687 --- [ Thread-2] o.s.b.a.mongo.embedded.EmbeddedMongo : 2018-11-27T18:56:05.741+0200 I CONTROL [initandlisten] MongoDB starting : pid=73690 port=50303 dbpath=/var/folders/pf/qp_pv2xn7xb7ysnltp6tc97cstys_v/T/embedmongo-db-c2738896-198f-4934-87c4-3bd773508af7 64-bit host=MBP15-N5AXG8WP
2018-11-27 18:56:05.742 INFO 73687 --- [ Thread-2] o.s.b.a.mongo.embedded.EmbeddedMongo : 2018-11-27T18:56:05.741+0200 I CONTROL [initandlisten] db version v3.5.5
2018-11-27 18:56:05.742 INFO 73687 --- [ Thread-2] o.s.b.a.mongo.embedded.EmbeddedMongo : 2018-11-27T18:56:05.741+0200 I CONTROL [initandlisten] git version: 98515c812b6fa893613f063dae568ff8319cbfbd
2018-11-27 18:56:05.742 INFO 73687 --- [ Thread-2] o.s.b.a.mongo.embedded.EmbeddedMongo : 2018-11-27T18:56:05.741+0200 I CONTROL [initandlisten] allocator: system
Config
#EnableReactiveMongoRepositories
public class MongoReactiveApplication {
#Value("${spring.data.mongodb.uri}")
private String mongoUri;
#Bean
public MongoClient mongoClient() {
return MongoClients.create(mongoUri);
}
}
yaml
spring.data.mongodb.uri: mongodb://localhost:27017/mongotest
How should I change configuration to use external mongo?
Adding these beans helped me to connect to my external mongo
#Value("${spring.data.mongodb.uri}")
private String mongoUri;
#Bean
public MongoClient mongoClient() {
return MongoClients.create(mongoUri);
}
#Bean
public ReactiveMongoTemplate reactiveMongoTemplate() {
return new ReactiveMongoTemplate(reactiveMongoDatabaseFactory());
}
#Bean
public ReactiveMongoDatabaseFactory reactiveMongoDatabaseFactory() {
return new SimpleReactiveMongoDatabaseFactory(mongoClient(), "mongotest");
}
Try this
spring:
data:
mongodb:
uri: mongodb://localhost:27017/mongotest

Spring Boot will not start when using Spring Integration and JdbcMetadataStore

I am trying to use Spring Integration to read files via SFTP and to use multiple servers to only read each file once. I have configured the SFTP reader within Spring Boot and it works with the in-memory metadata store. When I configure the JdbcMetadataStore using Postgres, Spring boot will no longer start and there is no error message other than Tomcat is shutting down. I am using Spring Boot with JPA and Spring WS
2018-10-22 11:16:06.098 INFO 6775 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'dataSource' has been autodetected for JMX exposure
2018-10-22 11:16:06.106 INFO 6775 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Bean with name 'metadataStore' has been autodetected for JMX exposure
2018-10-22 11:16:06.114 INFO 6775 --- [ restartedMain] o.s.j.e.a.AnnotationMBeanExporter : Located managed bean 'metadataStore': registering with JMX server as MBean [org.springframework.integration.jdbc.metadata:name=metadataStore,type=JdbcMetadataStore]
2018-10-22 11:16:06.125 INFO 6775 --- [ restartedMain] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
I am using annotation based configuration
#Bean
public ConcurrentMetadataStore metadataStore(final DataSource dataSource) {
return new JdbcMetadataStore(dataSource);
}
#Bean
public SessionFactory<ChannelSftp.LsEntry> sftpSessionFactory() {
final DefaultSftpSessionFactory factory = new DefaultSftpSessionFactory(true);
factory.setHost(this.host);
factory.setPort(this.port);
factory.setUser(this.username);
factory.setPassword(this.password);
factory.setAllowUnknownKeys(true);
return new CachingSessionFactory<>(factory);
}
#Bean
#InboundChannelAdapter(channel = "stream", poller = #Poller(fixedDelay = "5000"))
public MessageSource<InputStream> sftpMessageSource(ConcurrentMetadataStore metadataStore) {
final SftpStreamingMessageSource messageSource = new SftpStreamingMessageSource(template(), null);
messageSource.setRemoteDirectory("/");
messageSource.setFilter(new SftpPersistentAcceptOnceFileListFilter(metadataStore,
"INT_"));
//messageSource.setFilter(new SftpPersistentAcceptOnceFileListFilter(new SimpleMetadataStore(),
// "streaming"));
return messageSource;
}
#Bean
#Transformer(inputChannel = "stream", outputChannel = "data")
public org.springframework.integration.transformer.Transformer transformer() {
return new StreamTransformer();
}
#Bean
public SftpRemoteFileTemplate template() {
return new SftpRemoteFileTemplate(sftpSessionFactory());
}
I noticed it failed when trying to load the metadatastore to JMX. I then disabled JMX in Spring Boot and it fixed the issue. Not sure why it was failing to add the bean to JMX but disabling JMX in the spring boot property(yml) file fixed the issue.
spring:
jmx:
enabled: false

Resources