having more issues with seting up hibernate with spring3. this time it is saying that connection is nul as the dialect is not set which it is on my hibernate.cfg.xml file.
here is the full exception:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mySessionFactory' defined in URL [file:war/WEB-INF/datasource-config.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Connection cannot be null when 'hibernate.dialect' not set
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:567)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:96)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:44)
at org.springframework.test.context.TestContext.buildApplicationContext(TestContext.java:198)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:233)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:126)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:85)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:95)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:139)
at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUnit4ClassRunner.java:51)
at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4ClassRunner.java:44)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:27)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:37)
at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4ClassRunner.java:42)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.hibernate.HibernateException: Connection cannot be null when 'hibernate.dialect' not set
at org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:97)
at org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:67)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:172)
at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:71)
at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2270)
at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2266)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1735)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1775)
at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:184)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:314)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
... 29 more
Here is my dataSource-config.xml thats ets up the sessionfactory
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password} " />
</bean>
<bean id="mySessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="packagesToScan" value="com.jr.freedom"/>
<property name="hibernateProperties" value="classpath:hibernate.cfg.xml"/>
</bean>
<!-- Declare a transaction manager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="mySessionFactory" />
</beans>
And below is the hibernate.cfg.xml file
<?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>
<!-- JDBC connection settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/freedom</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<!-- JDBC connection pool, use Hibernate internal connection pool -->
<property name="connection.pool_size">25</property>
<!-- Defines the SQL dialect used in Hiberante's application -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Display and format all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<!-- Mapping to hibernate mapping files -->
<!--mapping resource="org/kodejava/example/hibernate/app/Label.hbm.xml"/-->
</session-factory>
</hibernate-configuration>
As you can see, the dialect is being set.
edit: my database.properties file
# DB properties file
database.url=jdbc:mysql://localhost:3306/freedom
database.driver=com.mysql.jdbc.Driver
database.user=root
database.password=password
database.maxConnections=25
edit: here is a full stack trace. accessing the database could be the issue but i can succefully access it via command prompt?
2288 [main] WARN org.hibernate.engine.jdbc.internal.JdbcServicesImpl - HHH000342: Could not obtain connection to query metadata : Cannot create PoolableConnectionFactory (Access denied for user 'root'#'localhost' (using password: YES))
2289 [main] INFO org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#4f549ceb: defining beans [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.validation.beanvalidation.LocalValidatorFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,org.springframework.web.servlet.config.viewControllerHandlerMapping,userService,myDataSource,mySessionFactory,transactionManager,propertyConfigurer,org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0,viewResolver,org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0,hello,userController,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.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
2289 [main] DEBUG org.springframework.beans.factory.support.DisposableBeanAdapter - Invoking destroy method 'close' on bean with name 'myDataSource'
2289 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#14': [org.springframework.web.servlet.config.viewControllerHandlerMapping]
2289 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#8': [org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0]
2289 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)#1': [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0]
2290 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Retrieved dependent beans for bean '(inner bean)': [org.springframework.web.servlet.handler.MappedInterceptor#0]
The database connection is missing. Add to your hibernate.cfg.xml file a lines like this
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/your_database
</property>
<property name="connection.username">your_user</property>
<property name="connection.password">your_password</property>
(replace localhost if the database is not installed on your computer, and set the values beginning with your_ in my example).
I had this error with JPA, then I just added this line to application.properties:
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
based on this post: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
I had the same problem. Switching from the Apache Commons DataSource:
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${database.driver}" />
<property name="url" value="${database.url}" />
<property name="username" value="${database.user}" />
<property name="password" value="${database.password} " />
</bean>
To C3P0:
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://ipadress:3306/schema" />
<property name="user" value="root" />
<property name="password" value="abc" />
</bean>
made my problem go away. Maybe someone can explain why, I am just happy it works and wanna share what little I know :)
I think its the problem of not loading your hibernate.cfg.xml file in your application.
I too got the same problem. I have tried with the following code in my project:
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
Then it has worked fine.
Hope this will help.
This issue comes if your mysql-connector version and mysql-installer version is different.
Internally it will throw Caused by:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Client does not support authentication protocol requested by server; consider upgrading MySQL client.
So you need make your mysql-connector version and mysql-installer version same...
I you are using hibernate and InnoDB why don't you set the hibernate.dialect to org.hibernate.dialect.MySQL5 or org.hibernate.dialect.MySQL.
and the connection property to hibernate.connection.url.
i think you are not configure hibernate.cfg.xml.
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
SessionFactory factory = configuration.buildSessionFactory();
I think your datasource-config.xml is not in classpath
instead of having this file in WEB-INF/datasource-config.xml
copy it to WEB-INF/classes/datasource-config.xml
Added the following in persistence.xml file,
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
You did't post your session factory initialization code. But I guess this is the same problem with this one
From Hibernate 4.3.2.Final, StandardServiceRegistryBuilder is introduced. Please follow this order to intialize, e.g.:
Configuration configuration = new Configuration();
configuration.configure("com/jeecourse/config/hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
Please double check your code.
I think you don't create the Configuration like below.
Configuration conf = new Configuration().configure();
Best
I think the error cased by unloading hibernate.cfg.xml file after you have created the Configuration Object like this:
Configuration config = new Configuration();
config.configure("hibernate.cfg.xml");
I had the the same problem and the issue was, that my computer was not entered in the pg_hba.conf of the postgres database that allows which Clients(IP-Adresses) are allowed to speak with the database.
btw: Other users tells that the error raises too if they simply forget starting database service locally
Creation of ServiceRegistry instance separately and pass it to buildSessionFactory may cause this error. Try to create SessionFactory instance as follows:
private static SessionFactory factory;
factory = cfg.buildSessionFactory(
new ServiceRegistryBuilder().applySettings(cfg.getProperties())
.buildServiceRegistry());
We were recently facing the same issue with one of our deployment, as we were also using hibernate and dialect is null is a vague error.
I use was with connection string itself and did the changes below to make it work
connectionUrl :- jdbc:mysql://127.0.0.1:3306/{{dbName}}?serverTimezone=UTC&allowPublicKeyRetrieval=true&useSSL=false
Steps how did we solve it
1) We ran simple DB connection with JDBC driver that will gave the exception of time zone.
2) we found the issue with time zone and had to add more properties in connection string as show above.
3) We also added 2 other properties as still it was not working.
Dialect is not set is vague to took lot of our time, I hope this helps.
This worked for me added the dialect property...
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
<persistence-unit name="project_name" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.schema-generation.drop-source" value="script-then-metadata"/>
<property name="dialect" value="org.hibernate.dialect.MySQLDialect"/>
</properties>
</persistence-unit>
</persistence>
I face this problem when I project update , the error is javax.persistence.jdbc.url', 'hibernate.connection.url', or 'hibernate.dialect'
and I found the solution. it work fine.
here is the details solution
Related
I'm working a series of tutorial apps to go over different Java EE technologies. I'm following various tutorials and more or less stick to them. Recently, I started putting together a simple Spring CRUD webapp to store, find, modify, and delete employees in an Employee DB table. I have previously completed another, very similar app, which only used plain Java and Hibernate, and which aimed to achieve the exact same functionality. That app worked alright, so I decided to copy over the database connection settings from this old app to the new, Spring one.
Problem is, the Spring DriverManagerDataSource bean does not seem to accept setting of the same properties as the original Hibernate configuration did, for example "hibernate.hbm2ddl.auto", which I want for conveniently wiping out the DB at startup, or "defaultSchema", which Postgres requires for some reason, so I'm stuck at configuring the DB connection.
How do I get Spring to accept these properties the same as Hibernate in the old app did, and to exhibit the same behavior? Why isn't the bean accepting these particular properties in some predictable, sensible way, like there is for other properties such as "url" or "password"? Am I even supposed to be setting them, isn't there some other mechanism in Spring that takes care of the functionality that I want from the properties?
Old app config:
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/test2</property>
<property name="connection.username">postgres</property>
<property name="connection.password">postgres</property>
<property name="hibernate.default_schema">public</property>
<property name="show_sql">true</property>
<property name="use_sql_comments">true</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping class="cz.bsc.hibernatetest.hibernatetutorial.domain.Book" />
<mapping class="cz.bsc.hibernatetest.hibernatetutorial.domain.Author" />
</session-factory>
</hibernate-configuration>
Part of the Spring config taken from the tutorial which I attempt to modify as described above:
spring-servlet.xml
<beans...>
<bean id="ds"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"></property>
<property name="url" value="jdbc:postgresql://localhost:5432/test2"></property>
<property name="username" value="postgres"></property>
<property name="password" value="postgres"></property>
<property name="spring.jpa.hibernate.defaultSchema" value="public"></property>
<property name="spring.jpa.hibernate.show_sql" value="true"></property>
<property name="spring.jpa.hibernate.use_sql_comments" value="true"></property>
<property name="spring.jpa.hibernate.hbm2ddl.auto" value="create"></property>
</bean>
</beans>
Complete error message that my app in its current shape throws. I presume that it indicates that I'm attempting to set a property in a way that is not intended, so a syntax error of sorts.
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'empController': Unsatisfied dependency expressed through field 'dao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dao' defined in ServletContext resource [/WEB-INF/spring-servlet.xml]: Cannot resolve reference to bean 'jt' while setting bean property 'template'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jt' defined in ServletContext resource [/WEB-INF/spring-servlet.xml]: Cannot resolve reference to bean 'ds' while setting bean property 'dataSource'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ds' defined in ServletContext resource [/WEB-INF/spring-servlet.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'spring.jpa.hibernate.defaultSchema' of bean class [org.springframework.jdbc.datasource.DriverManagerDataSource]: Nested property in path 'spring.jpa.hibernate.defaultSchema' does not exist; nested exception is org.springframework.beans.NotReadablePropertyException: Invalid property 'spring' of bean class [org.springframework.jdbc.datasource.DriverManagerDataSource]: Bean property 'spring' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
Hibernates properties are not part of data-source definition.
It should defined under session-factory bean.
for example:
<beans>
<bean id="ds"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"></property>
<property name="url" value="jdbc:postgresql://localhost:5432/test2"></property>
<property name="username" value="postgres"></property>
<property name="password" value="postgres"></property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref bean="ds" />
<property name="packagesToScan" value="db entities package name" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.defaultSchema">public</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.use_sql_comments">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Need some clarification and helps. Especially appreciate describing general concepts or link where they are described.
So, on the hibernate website I have read the next one:
For use inside an application server, you should almost always
configure Hibernate to obtain connections from an application server
javax.sql.Datasource registered in JNDI. You will need to set at least
one of the following properties:
And I have a few question because at the moment I am really confused about all of that stuff with DataSource, DataDriver, Tomcat and Hibernate in general.
Does configuring Datasource and binding SessionFactory to the JNDI
is the same process?
If no, for what we use DataSource and for why we need to bind SessionFactory to JNDI (in general)?
Am I understood right? If we configure DataSource in hibernate.cfg.xml file we don't need to configure it in {tomcat}/conf/server.xml or {tomcat}/conf/context.xml?
What is hibernate.jndi.url? Does it is the same as hibernate.connection.url?
What is hibernate.connection.datasource? In docs I read that it is "datasource JNDI name", so if I understood right it can be any name?
From Hibernate docs I read that setting at least one of the properties hibernate.connection.datasource, hibernate.jndi.url, hibernate.jndi.class, hibernate.connection.username, hibernate.connection.password makes my app use javax.sql.Datasource registered in JNDI. So does the next conf already configured to use DataSource?
How to check that DataSource used and configured fine?
My hibernate.cfg.xml file:
<?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.show_sql">true</property>
<property name="hibernate.use_sql_comments">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.generate_statistics">true</property>
<!--http://stackoverflow.com/questions/2067526/hibernate-connection-pool-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!--For use inside an application server, you should almost always configure Hibernate to obtain connections from an application server javax.sql.Datasource registered in JNDI. You will need to set at least one of the following properties:-->
<!--hibernate.connection.datasource,hibernate.jndi.url,hibernate.jndi.class,hibernate.connection.username,hibernate.connection.password-->
<!--Datasource config-->
<property name="hibernate.connection.datasource">jdbc:mysql://localhost/easywordweb</property>
<!--<property name="hibernate.jndi.url">??????? what is it</property>-->
<!--/Datasource config-->
<!--*****************************************************************-->
<!--C3P0 config-->
<!--Hibernate will obtain and pool connections using java.sql.DriverManager if you set the 5 following properties -->
<!--hibernate.connection.driver_class,hibernate.connection.url,hibernate.connection.username,hibernate.connection.password,hibernate.connection.pool_size-->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/easywordweb</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.connection.password">password</property>
<!--We can use a third party pool for best performance and stability, for example c3p0. Just replace the hibernate.connection.pool_size property with connection pool specific settings. This will turn off Hibernate's internal pool. For example, you might like to use c3p0. -->
<!--<property name="hibernate.connection.pool_size">140</property>-->
<property name="hibernate.c3p0.max_size">140</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.acquire_increment">5</property>
<!--max to cache-->
<property name="hibernate.c3p0.max_statements">50</property>
<!--The seconds a Connection can remain pooled but unused before being discarded. Zero means idle connections never expire. Hibernate default: 0-->
<property name="hibernate.c3p0.timeout">21600</property>
<!--for test, change futher-->
<property name="hibernate.c3p0.preferredTestQuery">SELECT 1;</property>
<!--at every connection checkin to verify that the connection is valid-->
<property name="hibernate.c3p0.testConnectionOnCheckout">true</property>
<!--at every connection checkout to verify that the connection is valid-->
<property name="hibernate.c3p0.testConnectionOnCheckin">true</property>
<!--/for test, change futher-->
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<!--/C3P0 config-->
<!--*****************************************************************-->
<property name="hibernate.c3p0.validate">true</property>
<!--c3p0 will test all idle, pooled but unchecked-out connections, every this number of seconds-->
<property name="hibernate.c3p0.idle_test_period">21000</property>
<property name="hibernate.jdbc.batch_size">20</property>
<!--Number rows to be returned if no setted-->
<property name="hibernate.jdbc.fetch_size">20</property>
<property name="hibernate.jdbc.use_get_generated_keys">true</property>
<property name="hibernate.temp.use_jdbc_metadata_defaults">false</property>
<!--FIXING: Table "...".hibernate_sequence table not found.-->
<property name="hibernate.id.new_generator_mappings">false</property>
</session-factory>
</hibernate-configuration>
Thank's everyone in advance.
In the config you have posted you are initializing the connection pool within your application.
An alternative is to delegate the creation of the database pool to your app/web server and expose it as a JNDI resource. Your application need then only specify the name of the JNDI datasource to obtain a connection.
Doing this in Tomcat is documented here:
https://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html
Your hibernate.cfg.xml then looks like:
<?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.show_sql">true</property>
<property name="hibernate.use_sql_comments">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.generate_statistics">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- The Server configured JNDI datasource -->
<property name="hibernate.connection.datasource">java:comp/env/jdbc/MyLocalDB</property>
<property name="hibernate.jdbc.batch_size">20</property>
<!--Number rows to be returned if no setted-->
<property name="hibernate.jdbc.fetch_size">20</property>
<property name="hibernate.jdbc.use_get_generated_keys">true</property>
<property name="hibernate.temp.use_jdbc_metadata_defaults">false</property>
<!--FIXING: Table "...".hibernate_sequence table not found.-->
<property name="hibernate.id.new_generator_mappings">false</property>
</session-factory>
</hibernate-configuration>
I have builded a java application(maven) to run on server.I use Eclipse Luna, Spring 4 and Hibernate 4.When I run it, I have an error:
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF//applicationContext.xml]: Invocation of init method failed; nested exception is org.hibernate.InvalidMappingException: Could not parse mapping document from input stream
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:736)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5016)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5528)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from input stream
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXml(Configuration.java:3762)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXmlQueue(Configuration.java:3751)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3739)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1410)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
at org.springframework.orm.hibernate4.LocalSessionFactoryBuilder.buildSessionFactory(LocalSessionFactoryBuilder.java:372)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:454)
at org.springframework.orm.hibernate4.LocalSessionFactoryBean.afterPropertiesSet(LocalSessionFactoryBean.java:439)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1633)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1570)
... 21 more
Caused by: org.hibernate.DuplicateMappingException: Duplicate class/entity mapping com.hibernate.data.Person
at org.hibernate.cfg.Configuration$MappingsImpl.addClass(Configuration.java:2835)
at org.hibernate.cfg.HbmBinder.bindRoot(HbmBinder.java:178)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXml(Configuration.java:3759)
... 31 more
Searching similar questions on web,I thought it occurs due to lack of some hibernate dependencies and added them.But it didn't work.Now, I am out of ideas!
My project is here: https://github.com/fsel/Spring-Hibernate-JSF-MySQL-Eclipse-Integration/tree/master/Spring-Hibernate-JSF-MySQL-Example
Any help would be appreciated.
Thanks!
The Person Class is loaded twice.
In Spring configuration - applicationContext.xml file you have :
<property name="mappingResources">
<list>
<value>domain-classes.hbm.xml</value>
</list>
</property>
Also in hibernate configuration - hibernate.cfg.xml file you are loading it once again:
<mapping resource="domain-classes.hbm.xml"/>
To fix the issue, just remove one of the above entries, either from Spring configuration file or Hibernate configuration file.
Caused by: org.hibernate.DuplicateMappingException: Duplicate class/entity mapping com.hibernate.data.Person
at org.hibernate.cfg.Configuration$MappingsImpl.addClass(Configuration.java:2835)
at org.hibernate.cfg.HbmBinder.bindRoot(HbmBinder.java:178)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXml(Configuration.java:3759)
above exception convey that there are duplicate mapping for com.hibernate.data.Person
your hinernate.cfg.xml has below code
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/PERSONDB</property>
<property name="hibernate.connection.username">fulden</property>
<property name="hibernate.connection.password">secret_pass</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Specify session context -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- Show SQL -->
<property name="show_sql">true</property>
<!-- Referring Mapping File -->
<mapping resource="domain-classes.hbm.xml"/>
</session-factory>
</hibernate-configuration>
and your applicationContext.xml has below code
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!-- Enable Spring Annotation Configuration -->
<context:annotation-config />
<!-- Scan for all of Spring components such as Spring Service -->
<context:component-scan base-package="com.spring.service"></context:component-scan>
<!-- Create Data Source bean -->
<bean id="dataSource" 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/PERSONDB" />
<property name="username" value="fulden" />
<property name="password" value="secret_pass" />
</bean>
<!-- Define SessionFactory bean -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>domain-classes.hbm.xml</value>
</list>
</property>
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
</bean>
<!-- Transaction Manager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Detect #Transactional Annotation -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
if you closely observe both files you are duplicating hibernate mapping resource
In hibernate.cfg.xml
<mapping resource="domain-classes.hbm.xml"/>
In a applicatinContext.xml
<property name="mappingResources">
<list>
<value>domain-classes.hbm.xml</value>
</list>
</property>
solution:
removing mappingResources property from applicatinContext.xml file should resolve you problem
thank you
You do not have a constructor without arguments in Person.
Hibernate, and code in general that creates objects via reflection use
Class.newInstance() to create a new instance of your classes. This
method requires a public no-arg constructor to be able to
instantiate the object. For most use cases, providing a no-arg
constructor is not a problem.
Source :
Why does Hibernate require no argument constructor?
First of all, I have searched other similar questions here before.Though, I couldn't figure out where I have mistaken.
In Eclipse, I have been building a simple Hibernate+Spring+MySQL+Maven project recently.I am having trouble at the stage of database&java connection.When I run the project, it gives the the following error:
WARN : org.hibernate.internal.util.xml.DTDEntityResolver - HHH000223:Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
WARN : org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator - HHH000181: No appropriate connection provider encountered, assuming application will be supplying connections
Transaction began Exception in thread "main" org.hibernate.HibernateException: save is not valid without active transaction
at org.hibernate.context.internal.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:352)
at com.sun.proxy.$Proxy19.save(Unknown Source)
at com.test.Main.main(Main.java:33)
The main class:
package com.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import com.hibernate.data.Person;
public class Main {
public static void main(String [] args){
// Create a configuration instance
Configuration configuration = new Configuration();
// Provide configuration file
configuration.configure("hibernate.cfg.xml");
// Build a SessionFactory
SessionFactory factory = configuration.buildSessionFactory(new StandardServiceRegistryBuilder().configure().build());
// Get current session, current session is already associated with Thread
Session session = factory.getCurrentSession();
// Begin transaction, if you would like save your instances, your calling of save must be associated with a transaction
Transaction tx = session.getTransaction();
// Create person
Person newPerson = new Person();
newPerson.setFirstName("Peter");
newPerson.setLastName("Jackson");
newPerson.setGender("Male");
newPerson.setAge(30);
//Save
session.save(newPerson);
session.flush();
tx.commit();
session.close();
}
}
hbm.xml file:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class table="Person" lazy="false" name="com.hibernate.data.Person" >
<id column="PERSON_ID" type="int" name="id" >
<generator class="increment"/>
</id>
<property name="firstName" column="PERSON_FIRSTNAME" type="string" />
<property name="lastName" column="PERSON_LASTNAME" type="string" />
<property name="gender" column="PERSON_GENDER" type="string" />
<property name="age" column="PERSON_AGE" type="int" />
</class>
</hibernate-mapping>
hibernate.cfg.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/PERSONDB</property>
<property name='connection.username'>root</property>
<property name='connection.password'>root</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Specify session context -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- Show SQL -->
<property name="show_sql">true</property>
<!-- Referring Mapping File -->
<mapping resource="domain-classes.hbm.xml"/>
<mapping class="com.hibernate.data.Person"/>
</session-factory>
</hibernate-configuration>
applicationContext.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<!-- Enable Spring Annotation Configuration -->
<context:annotation-config />
<!-- Scan for all of Spring components such as Spring Service -->
<context:component-scan base-package="com.spring.service"></context:component-scan>
<!-- Create Data Source bean -->
<bean id="dataSource" 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/PERSONDB" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<!-- Define SessionFactory bean -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mappingResources">
<list>
<value>domain-classes.hbm.xml</value>
</list>
</property>
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
</bean>
<!-- Transaction Manager -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- Detect #Transactional Annotation -->
<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
How can I fix this?
You forgot to begin the transaction:
Transaction tx = session.getTransaction();
tx.begin();
or, easier:
Transaction tx = session.beginTransaction();
Note that your problem is unrelated to Spring, since you're not using Spring at all in the posted code. When you do, you'll have to fix your Spring configuration: don't use classes from the hibernate3 package, since you're using hibernate4. Also, learn to use annotations and not hbm.xml files to map your entities. XML was useful in Java 1.4. But we're noaw at Java 1.8.
I'm trying to use Spring's JdbcTemplate to simplify my DAOs in a Java web service that is deployed in Tomcat and connects to Postgres.
I'm following Spring's documention, and I'm trying configure a DataSource in the application context file, as follows:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="com.manta" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${driverClassName}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
<context:property-placeholder location="/WEB-INF/db.properties"/>
</beans>
I have the following db.properties file in the appropriate place:
driverClassName=org.postgresql.Driver
url=jdbc:postgresql://pgprod.ecnext.com:5432/manta
username=my_user_name
password=my_password
When I try to deploy, I find the following stack trace in catalina.out:
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanDefinitionStoreException:
Invalid bean definition with name 'dataSource' defined in ServletContext resource [/WEB-INF/context.xml]:
Could not resolve placeholder 'driverClassName'
at org.springframework.beans.factory.config.PlaceholderConfigurerSupport.doProcessProperties(PlaceholderConfigurerSupport.java:209)
at org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.processProperties(PropertyPlaceholderConfigurer.java:220)
at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:84)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:681)
at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:656)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:446)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:385)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:284)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4765)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5260)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:866)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:842)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:615)
at org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:958)
at org.apache.catalina.startup.HostConfig$DeployWar.run(HostConfig.java:1599)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:679)
Things that are NOT the problem:
The db.properties file is in the correct location.
The credentials in the db.properties are correct, and can be read in manually to connect to the database.
The context.xml file is being found by the ContextLoaderListener, and I am able to inject other dependencies.
I would very much appreciate any suggestions as to what could cause this. I'm using Spring 3.1.1, and Tomcat 7.0.26.
You probably have multiple <context:property-placeholder ... > in your project which each create a new instance of the underlying object, and is a doorway to pains...
I prefer using the following declaration for loading property files:
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:db-config.properties</value>
</list>
</property>
<property name="ignoreUnresolvablePlaceholders" value="true" />
</bean>
Drop the leading slash from your location (i.e. location="WEB-INF/db.properties" ) or better yet change it to classpath:
location="classpath:db.properties"
use org.springframework.jdbc.datasource.DriverManagerDataSource
instead of org.apache.commons.dbcp.BasicDataSource
Use ignore-unresolvable="true" in you application context. Default value is 'fales' you need to set it 'true' so pass on the key to any others in the context that have not yet visited.
<context:property-placeholder ignore-unresolvable="true" location="/WEB-INF/application.properties" />
<context:property-placeholder ignore-unresolvable="true" location="/WEB-INF/dbcp.properties"/>
Make sure you have the maven dependency properly, Sping-core and Spring-context dependencies should be present in your project.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version></version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version></version>
</dependency>