'hibernate.dialect' must be set when no Connection available - spring

I am trying to run a hello world for: Spring/Hibernate with HSQLDB and C3PO connection pool.
the same code works with mySQL (only with different dialect and driver)
I have run the database and I can connect to it with the swing GUI. But when I try to run my application, I am getting a start up error.
Here are the details:
1: the error -
INFO: Initializing Spring root WebApplicationContext
[ERROR] [pool-2-thread-1 05:20:08] (JDBCExceptionReporter.java:logExceptions:101) Connections could not be acquired from the underlying database!
[ERROR] [pool-2-thread-1 05:20:08] (ContextLoader.java:initWebApplicationContext:220) Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/hibernate-context.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: 'hibernate.dialect' must be set when no Connection avalable
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1420)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
...
...
2: hibernate-context.xml -
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.gleeb.sample.model" />
<property name="hibernateProperties">
<props>
<!-- <prop key="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop> -->
<prop key="dialect">org.hibernate.dialect.HSQLDialect</prop>
<prop key="show_sql">false</prop>
<prop key="hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close" p:driverClass="org.hsqldb.jdbc.JDBCDriver"
p:jdbcUrl="jdbc:hsqldb:hsql://localhost/testdb" p:user="sa"
p:password="" p:acquireIncrement="5" p:idleConnectionTestPeriod="60"
p:maxPoolSize="100" p:maxStatements="50" p:minPoolSize="10" />
<!-- Declare a transaction manager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />

As far as I can tell, it is not possible to pass in the dialect as a value set on the hibernateProperties field of a Spring Session Factory, at least if you are also using the configLocation property on it.
My hibernate.cfg.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.DB2Dialect</property>
<property name="hibernate.search.autoregister_listeners">false</property>
[etc...]
My relevant session factory context config:
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="dataSource" ref="dataSource"/>
<property name="hibernateProperties">
<props>
<!--<prop key="hibernate.dialect">org.hibernate.dialect.DB2Dialect</prop>-->
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.generate_statistics">false</prop>
<prop key="hibernate.default_schema">xxx</prop>
</props>
</property>
</bean>
If I uncomment the dialect prop in the context file, and comment it out from in the hibernate.cfg.xml file I encounter the same exception as the OP:
Caused by: org.hibernate.HibernateException: Connection cannot be null when 'hibernate.dialect' not set
However if I run with the above configuration (commented out in the context file, uncommented in the hibernate.cfg.xml), it works, and I see the formatted hibernate SQL, showing that the other hibernate properties are being set by the context file.

I have session factory properties with hibernate. prefix.
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.HSQLDialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=false
hibernate.format_sql=false
</value>
</property>

Related

Why does Flexy-Pool cause a NoSuchElementException when configured via Spring in Apache Storm

I have an Apache Storm (1.1.1) based application, which uses Spring (5.0.3) to configure and inject Hibernate-based (5.2.12) database services, which connect to a PostgreSQL database.
Between Hibernate and the database, I have configured flexy-pool (2.0.0) on top of HikariCP (2.7.6) as a datasource (see Figure A). The application is launched on some Ubuntu 16.04 LTS server instances with the latest OpenJDK 8 version.
I experience sad runtime exceptions related to flexy-pool after starting my Storm topology. However, this is not deterministic. Sometimes it will work, sometimes the exception below will be thrown. If I do not use flexy-pool in my application (see Figure B) everything works everytime as expected.
Caused by:
org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.vladmihalcea.flexypool.config.Configuration]: Factory method 'build' threw exception; nested exception is java.util.NoSuchElementException at
org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) at
org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:579) ... 42 more
Caused by:
java.util.NoSuchElementException at
sun.misc.URLClassPath$1.nextElement(URLClassPath.java:282) at
sun.misc.URLClassPath$1.nextElement(URLClassPath.java:256) at
java.net.URLClassLoader$3$1.run(URLClassLoader.java:603) at
java.net.URLClassLoader$3$1.run(URLClassLoader.java:599) at
java.security.AccessController.doPrivileged(Native Method) at
java.net.URLClassLoader$3.next(URLClassLoader.java:598) at
java.net.URLClassLoader$3.hasMoreElements(URLClassLoader.java:623) at
sun.misc.CompoundEnumeration.next(CompoundEnumeration.java:45) at
sun.misc.CompoundEnumeration.nextElement(CompoundEnumeration.java:58) at
java.util.ServiceLoader$LazyIterator.hasNextService(ServiceLoader.java:357) at
java.util.ServiceLoader$LazyIterator.hasNext(ServiceLoader.java:393) at
java.util.ServiceLoader$1.hasNext(ServiceLoader.java:474) at
com.vladmihalcea.flexypool.metric.MetricsFactoryResolver.resolve(MetricsFactoryResolver.java:27) at
com.vladmihalcea.flexypool.config.Configuration$Builder.build(Configuration.java:165) 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:498) at
org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
The Spring configuration used in Figure B is this one (based on the official sample):
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
<property name="poolName" value="springHikariCP"/>
<property name="connectionTestQuery" value="SELECT 1"/>
<property name="dataSourceClassName" value="${gmetric.dataSourceClassName}"/>
<property name="dataSourceProperties">
<props>
<prop key="url">${shc.gmetric.url}</prop>
<prop key="user">${shc.gmetric.username}</prop>
<prop key="password">${shc.gmetric.pw}</prop>
</props>
</property>
</bean>
<bean id="poolingDataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
<constructor-arg ref="hikariConfig"/>
</bean>
<bean id="configurationBuilder" class="com.vladmihalcea.flexypool.config.Configuration$Builder">
<constructor-arg value="uniqueId"/>
<constructor-arg ref="poolingDataSource"/>
<constructor-arg value="#{ T(com.vladmihalcea.flexypool.adaptor.HikariCPPoolAdapter).FACTORY }"/>
</bean>
<bean id="configuration" factory-bean="configurationBuilder" factory-method="build"/>
<bean id="flexyPoolDataSource" class="com.vladmihalcea.flexypool.FlexyPoolDataSource" init-method="start" destroy-method="stop">
<constructor-arg ref="configuration"/>
<constructor-arg>
<array>
<bean class="com.vladmihalcea.flexypool.strategy.IncrementPoolOnTimeoutConnectionAcquiringStrategy.Factory">
<constructor-arg value="5"/>
</bean>
<bean class="com.vladmihalcea.flexypool.strategy.RetryConnectionAcquiringStrategy.Factory">
<constructor-arg value="2"/>
</bean>
</array>
</constructor-arg>
</bean>
<bean id="entityManagerFactoryGMetrics"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="flexyPoolDataSource"/>
<property name="persistenceUnitName" value="${gmetric.context.name}"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<!--<property name="generateDdl" value="true" />-->
<property name="databasePlatform" value="${hibernate.dialect}"/>
<property name="showSql" value="${hibernate.showSQL}"/>
</bean>
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.connection.driver_class">${gmetric.driverClassName}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.showSQL}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.current_session_context_class">thread</prop>
</props>
</property>
</bean>
My questions are:
Is my Spring-based (default) configuration for flexy-pool correct?
Is there a solution to prevent this runtime exception related to flexy-pool?
What is the cause for this NoSuchElementException?
I found, that Dropwizard Metrics 4 (which is required by flexy-pool) was missing in my shaded jar and therefore this wired runtime exception occured:
<dependency>
<groupId>io.dropwizard.metrics</groupId>
<artifactId>metrics-core</artifactId>
<version>${metrics.version}</version>
</dependency>
According to the author this is related to the way flexy-pool detects the related Dropwizard Metrics handler (as it supports DM3 and DM4, which cannot be used interchangeably).

Intellij JPA Console with persistence.xml

I'm setting up a xml-free persistence JPA/Hibernate 4+/Spring 3+ using Intellij 13+. When I try to execute a query in the jpa console, I get the following error:
javax.persistence.PersistenceException: Unable to build entity manager factory
java.lang.RuntimeException: org.hibernate.boot.registry.selector.spi.StrategySelectionException: Unable to resolve name [org.hibernate.dialect.PostgreSQL9Dialectt.PostgreSQL9Dialect] as strategy [org.hibernate.dialect.Dialect]
With the default postgres dialect, I get the same error.
Any idea what's going on?
Configuration extract:
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.wikiz.service.model.rep" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="jadira.usertype.autoRegisterUserTypes">true</prop>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
</props>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.user}"/>
<property name="password" value="${db.pass}"/>
</bean>
And variables:
hibernate.dialect=org.hibernate.dialect.PostgreSQL9Dialect
hibernate.show_sql=true
hibernate.format_sql=true
hibernate.hbm2ddl.auto=create
Ok here it is.
I am not 100% sure if this helps your case but I think this is what you need to do:
Add a jdbc connection to your database from the database tab (usually to your right)
Then add the hibernate facet to your module
Go to modules (alt+ctrl+shift+s) then add it:
Now you have enabled the persistance tab on your left (usually) and you can assign a datasource to your
Now add the hibernate configuration but you have to add the xml file of hibernate. I haven't tried it with just adding the spring application context instead of hibernate.cfg.xml. Maybe it will work...
Now you have enable the presistance configuration for intellij and you can assign a datasource to it.
Select that datasource that you want and you will be able to use the JPA console with your jpa POJOs and HSQLs

Cannot get current session

`
classpath:database.properties
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
<property name="packagesToScan" value="org.entity">
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven/>
<!-- not working -->
<!-- <context:component-scan base-package="org.service"></context:component-scan> -->
`
this is my spring configuration file. Problem is that i am not getting current session in my repository classes which are marked with #Repository, I have annotated my service methods with #Transactional annotation.
However all the autowiring is working fine, the only problem is when i try to get current session in repository classes, and if I use bean tag to instantiate my repository and service beans it works. What am i doing wrong here?
Use the OpenSessionInView Filter or similar, that way you should have a Session available during the request lifecycle (Controller/ View rendering).

spring transaction and aop

I'm writing a simple application with spring, I defined my daos and services with spring annotations and defined hibernate as the orm and transaction manager like this:
<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:env/hibernate.cfg.xml</value>
</property>
<property name="packagesToScan">
<list>
<value>com.skyfence.management.cm.model</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
like you can see I'm using annotations for the transactions management,
Until this point everything works fine.
Then I added a Logger Aspect to add log4j printouts before and after every method so I added the following to my applicationContext.xml
<aop:aspectj-autoproxy />
and created a new annotated aspect class:
#Aspect
#Component
public class LoggingAspect
{
}
The problem is that from that point hibernate is no longer working and I'm getting the following exception:
org.hibernate.HibernateException: No Session found for current thread
I suspect that somehow by adding the aspect the transactions stopped working but I have no idea how to solve it
Any help will be appreciated,

Overriding global jta timeout in spring context in weblogic

Our Weblogic have global JTA timeout 30s, since our server is under high load setting such global timout to a bigger value can be critical for performace of the application.
So I want to override this JTA timeout with specific value in context of particular service.
I have root context for a number of webservices it has it's own global transaction manager:
<bean id="jtaTransactionManager" class="org.springframework.transaction.jta.WebLogicJtaTransactionManager">
<property name="transactionManagerName" value="javax.transaction.TransactionManager"/>
</bean>
annotation driven for this transation manager is on
<tx:annotation-driven proxy-target-class="true" transaction-manager="jtaTransactionManager"/>
and i have global hibernate session factory :
<bean id="parent.session.factory"
abstract="true"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
destroy-method="destroy"
p:dataSource-ref="dataSource.schedules">
<property name="hibernateProperties">
<props>
<prop key="hibernate.transaction.manager_lookup_class">
org.hibernate.transaction.WeblogicTransactionManagerLookup
</prop>
<prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JTATransactionFactory</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
<prop key="hibernate.cache.use_query_cache">false</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.connection.autocommit">false</prop>
</props>
</property>
</bean>
Then I have the context of my webservice where I want to override the jta timeout:
Inherited local transaction manager:
<bean id="localTransactionManager" parent="jtaTransactionManager">
<property name="defaultTimeout" value="120"/>
</bean>
Bean with javax TransactionManager interface for hibernate:
<bean id="localEETransactionManager" factory-bean="localTransactionManager"
factory-method="getTransactionManager">
<property name="transactionTimeout" value="120"/>
</bean>
Session factory for Hibernate with lolcaly overrided TransactionManager with EE interface (javax.transaction.TransactionManager)
<bean id="sessionFactory" parent="parent.session.factory">
<property name="jtaTransactionManager" ref="localEETransactionManager"/>
<property name="annotatedClasses">
<list>
<value>com.example.City</value>
<value>com.example.State</value>
<value>com.example.Country</value>
</list>
</property>
</bean>
And finally the DAO with localy overrided WebLogicJtaTransactionManager:
<bean id="addressDao"
class="com.example.AddressDataAccessObjectImpl"
p:entityClass="com.example.City"
p:dataSource-ref="dataSource"
p:sessionFactory-ref="sessionFactory"
p:transactionManager-ref="localTransactionManager"/>
But when I run my application hibernate throws Caused by: weblogic.transaction.internal.TimedOutException: Transaction timed out after 30 seconds
And rolls back the transaction.
Maybe someone know what I'm doing wrong with those overrides?
PS This override works only for root context, if I do somthing like that:
<bean id="jtaTransactionManager" class="org.springframework.transaction.jta.WebLogicJtaTransactionManager">
<property name="transactionManagerName" value="javax.transaction.TransactionManager"/>
<property name="defaultTimeout" value="120"/>
</bean>
But that is not what I whant because it is still global for all application.

Resources