configuring hibernate datasource in spring xml - spring

I get below error while running my web application. I had problems in configuring hibernate & spring with right jars. After i crossed that hurdle after working on it for hours, i am getting problem in hibernate datasource. The session factory and dao beans are getting initialized properly by spring
but when i access method in dao i get error...
INFO: Attestation_spring_hibernate was successfully deployed in 11,309 milliseconds.
INFO: before calling rateDAO.getCount()
INFO: inside getSessionFactory()
WARNING: StandardWrapperValve[dispatcher]: Servlet.service() for servlet dispatcher threw exception
java.lang.UnsupportedOperationException: Not supported by BasicDataSource
at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1062)
at org.hibernate.service.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:141)
at org.hibernate.internal.AbstractSessionImpl$NonContextualJdbcConnectionAccess.obtainConnection(AbstractSessionImpl.java:292)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.obtainConnection(LogicalConnectionImpl.java:214)
at org.hibernate.engine.jdbc.internal.LogicalConnectionImpl.getConnection(LogicalConnectionImpl.java:157)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.connection(StatementPreparerImpl.java:56)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$5.doPrepare(StatementPreparerImpl.java:161)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl$StatementPreparationTemplate.prepareStatement(StatementPreparerImpl.java:182)
at org.hibernate.engine.jdbc.internal.StatementPreparerImpl.prepareQueryStatement(StatementPreparerImpl.java:159)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1859)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1836)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1816)
at org.hibernate.loader.Loader.doQuery(Loader.java:900)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:342)
at org.hibernate.loader.Loader.doList(Loader.java:2526)
at org.hibernate.loader.Loader.doList(Loader.java:2512)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2342)
at org.hibernate.loader.Loader.list(Loader.java:2337)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:124)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1662)
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374)
at daoImpl.RateDAO.getRateById(RateDAO.java:149)
at controller.Controller1.welcome(Controller1.java:47)
Below is my application context.xml..
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test_amar"/>
<property name="username" value="root"/>
<property name="password" value=""/>
<property name="initialSize" value="2"></property>
<property name="maxActive" value="5"></property>
<property name="validationQuery" value="SELECT 1"/>
</bean>
<!-- Hibernate Session Factory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource"/>
<property name="packagesToScan">
<array>
<value>entities</value>
</array>
</property>
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
i use spring3 & hibernate4. It appears there is configuration error in my datasource. but i am not able to locate it.
From the server log below , i see that dao & session factory beans are instantiated properly.
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/dispatcher-servlet.xml]
INFO: JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning
INFO: JSR-330 'javax.inject.Named' annotation found and supported for component scanning
INFO: JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#1020cb7: defining beans [**controller1,rateDAO**,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping#0,urlMapping,viewResolver,indexController,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory#fca094
INFO: Mapped URL path [/controller1] onto handler 'controller1'
INFO: Mapped URL path [/controller1/*] onto handler 'controller1'
Kindly assist..

Accoording to the latest version, the method getConnection(user, password) is not supported, but hibernate should not be calling that method.
You can use the spring provided org.springframework.jdbc.datasource.DriverManagerDataSource or the com.mysql.jdbc.jdbc2.optional.MysqlDataSource from your MySQL connector package. (http://dev.mysql.com/doc/refman/5.0/en/connector-j-reference-configuration-properties.html)

try to add the following code in hibernate property
<prop key=" hibernate.dialect "> org.hibernate.dialect.MySQLDialect </prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.connection.username">root</prop>
<prop key="hibernate.connection.password">root</prop>
</props>

try to remove from hibernate.cfg.xml
<property name="hibernate.connection.password">your-password</property>
<property name="hibernate.connection.username">your-username</property>

The problem with
org.springframework.jdbc.datasource.DriverManagerDataSource
is that it does NOT provides pooling! I would move to Tomcat JDBC Connection Pool. That is by now IMHO the most efficient one.
<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">
It requires the dependency
org.apache.tomcat tomcat-jdbc
Check documentation:
https://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html

Try to use com.mysql.jdbc.jdbc2.optional.MysqlDataSource.

Related

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

Issue when trying to export spring bean as OSGI service

I wanted to export a bean as a OSGi service , so that this can be used in another bundle. But I get the below error. Please help.
SEVERE: Unable to create application context for [com.abc.test.impl], unsatisfied dependencies: Dependency on [(objectClass=com.abc.platform.test.manager.ITestManager)] (from bean [&testManager])
org.springframework.context.ApplicationContextException: Application context initialization for 'com.xyz.test.impl' has timed out waiting for (objectClass=com.abc.test.manager.ITestManager)
The code is given below.
Bundle 1 (com.abc.test.impl) :
Bean declaration -
<bean id="testManagerTarget" class="com.abc.platform.test.TestManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="testManager" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="target">
<ref bean="testManagerTarget" />
</property>
<property name="transactionAttributes">
<props>
<prop key="store">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
Declaring bean as OSGI service -
Text content in the code blocks is automatically word-wrapped
<osgi:service id="testManagerService" ref="testManager" interface="com.abc.platform.test.manager.ITestManager" />
Bundle 2 (com.xyz.test.impl):
<osgi:reference id="testManager" interface="com.abc.platform.test.manager.ITestManager" />
Really appreciate any help.
Thanks
Soniya

spring + hibernate + infinispan as 2nd level cache

I tried to setup infinispan as 2nd level cache for hibernate in spring+tomcat based app.
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${hibernate.connection.driver_class}"/>
<property name="url" value="${hibernate.connection.url}"/>
<property name="username" value="${hibernate.connection.username}"/>
<property name="password" value="${hibernate.connection.password}"/>
<property name="maxActive" value="${hibernate.connection.maxActive}"/>
<property name="maxIdle" value="${hibernate.connection.maxIdle}"/>
<property name="minIdle" value="${hibernate.connection.minIdle}"/>
<property name="maxWait" value="${hibernate.connection.maxWait}"/>
</bean>
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManager">
<bean class="com.arjuna.ats.jta.TransactionManager" factory-method="transactionManager"/>
</property>
<property name="userTransaction">
<bean class="com.arjuna.ats.jta.UserTransaction" factory-method="userTransaction"/>
</property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.example"/>
<!---->
<property name="hibernateProperties" ref="db-properties"/>
</bean>
And the properties are:
hibernate.cache.use_second_level_cache=true
hibernate.cache.use_query_cache=true
hibernate.cache.region.factory_class=org.hibernate.cache.infinispan.InfinispanRegionFactory
I get an exception:
Caused by: org.infinispan.CacheException: This is transactional cache but no transaction manager could be found. Configure the transaction manager lookup properly.
How do I configure a transaction manager lookup?
The easy answer for spring is to add (inside id="sessionFactory" spring XML configuration) :
<property name="jtaTransactionManager" ref="transactionManager"/>
This is available in spring 3.2.2.RELEASE (it maybe available in older spring versions too, I would guess since spring 3.1.x)
This should achieve what Steve Ebersole points at. This causes Spring to provide a JtaPlatform via the class https://github.com/SpringSource/spring-framework/blob/master/spring-orm-hibernate4/src/main/java/org/springframework/orm/hibernate4/ConfigurableJtaPlatform.java
See JavaDoc for class org.springframework.orm.hibernate4.LocalSessionFactoryBean (that you are using) concerning JTA usage.
Both Hibernate and Infinispan need to know about the TransactionManager. If you tell Hibernate about the TransactionManager, it will in turn tell Infinispan for you. I am guessing Spring has a way to tell Hibernate about the JTA setup, but I could not find it. Hibernate for its part (I see you are at least trying to use Hibernate 4) needs to be told about which org.hibernate.service.jta.platform.spi.JtaPlatform to use. org.hibernate.service.jta.platform.spi.JtaPlatform is the contract for Hibernate to know how to interact with the JTA environment.

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

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>

Could not initialize JBossWorkManagerTaskExecutor because JBoss API is not available: java.lang.reflect.InvocationTargetException

I have a requirement to configure JBoss WorkManager in my application. Earlier the configuration was as follows:
<bean id="taskExecutor" class="org.springframework.scheduling.commonj.WorkManagerTaskExecutor">
<property name="workManagerName" value="wm/default" />
</bean>
The clas "WorkManagerTaskExecutor" is intended for WebSphere and WebLogc. But we are migrating our application from WebSphere to JBOss. So I have the following configuration.
web.xml
<resource-ref id="ResourceRef_1163654014164">
<description>WorkManager</description>
<res-ref-name>WorkManager</res-ref-name>
<res-type>org.jboss.resource.work.JBossWorkManager</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
jboss-web.xml
<resource-ref id="ResourceRef_1163654014164">
<description>WorkManager</description>
<res-ref-name>WorkManager</res-ref-name>
<jndi-name>WorkManager</jndi-name>
<ignore-dependency/>
</resource-ref>
applicationContext.xml
<bean id="taskExecutor" class="org.springframework.jca.work.jboss.JBossWorkManagerTaskExecutor">
</bean>
Exception Log:
17:04:39,472 ERROR [LogInterceptor]
EJBException in method: public abstract com.test.ejb.timer.SLATimer com.test.ejb.timer.SLATimerHome.create() throws javax.ejb.CreateException,java.rmi.RemoteException, causedBy:
org.springframework.beans.factory.BeanCreationException
: Error creating bean with name 'taskExecutor' defined in class path resource [spring-messaging.xml]: Invocation of init method failed; nested exception is java.lang.IllegalStateException: Could not initialize JBossWorkManagerTaskExecutor because JBoss API is not available:
java.lang.reflect.InvocationTargetException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean (AbstractAutowireCapableBeanFactory.java:1420)
Caused by: java.lang.IllegalStateException: Could not initialize JBossWorkManagerTaskExecutor because JBoss API is not available:
java.lang.reflect.InvocationTargetException
Please help to fix the above issue.
Thanks
I am answering my question myself which may be helpful for somebody.
Removed configuration in web.xml and jboss.web.xml for this JBoss Work Manager.
Have the following configuration in applicationContext.xml
<bean id="jbossResourceAdapter" class="org.jboss.resource.adapter.jms.JmsResourceAdapter"/>
<bean id="mbeanServer" class="org.jboss.mx.util.MBeanServerLocator" factory-method="locateJBoss"/>
<bean id="chanduWorkManager" factory-bean="mbeanServer" factory-method="getAttribute">
<constructor-arg>
<bean class="org.springframework.jmx.support.ObjectNameManager" factory-method="getInstance">
<constructor-arg value="jboss.jca:service=ChanduWorkManager" />
</bean>
</constructor-arg>
<constructor-arg value="Instance" />
</bean>
<bean id="taskExecutor" class="org.springframework.jca.work.WorkManagerTaskExecutor">
<property name="workManager" ref="chanduWorkManager"/>
</bean>
<bean id="jbossResourceAdapterFactory" class="org.springframework.jca.support.ResourceAdapterFactoryBean">
<property name="resourceAdapter" ref="jbossResourceAdapter"/>
<property name="workManager" ref="taskExecutor"/>
</bean>
<bean id="jbossActivationSpecFactory" class="org.springframework.jms.listener.endpoint.StandardJmsActivationSpecFactory">
<property name="activationSpecClass" value="org.jboss.resource.adapter.jms.inflow.JmsActivationSpec"/>
<property name="defaultProperties">
<props>
<prop key="sessionTransacted">false</prop>
<prop key="minSession">1</prop>
<prop key="maxSession">15</prop>
</props>
</property>
</bean>
Hope it will help somebody.
Thanks,
Chandrasekhar Aadhanapattu
Find this may be the right answer....
In my case also AS is JBoss...
Spring WorkManagerTaskExecutor cannot initialize in websphere

Resources