I wonder if anyone can explain to me why a Spring and Hibernate webapp works perfectly well in two environments but fails in another? I'm using NetBeans 8.0.X with Tomcat 8.0.3.0 and Apache Derby 10.X.
My application's dispatcherservlet is as follows:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- Uses annotations in classes for JavaBeans. XML is an alternative. -->
<mvc:annotation-driven />
<!-- Base package. -->
<context:component-scan base-package="library" />
<!-- Model. -->
<bean id="person" class="library.model.Person" />
<bean id="book" class="library.model.Book" />
<!-- Spring Controllers. -->
<bean id="adminController" class="library.controller.admin.AdminController" />
<bean id="personController" class="library.controller.PersonController" />
<bean id="bookController" class="library.controller.BookController" />
<bean id="exceptionController" class="library.controller.ExceptionController" />
<!-- Spring Interceptors. -->
<mvc:interceptors>
<bean id="clientInterceptor" class="library.interceptor.ClientInterceptor" />
</mvc:interceptors>
<!-- Spring Services. -->
<bean id="personServiceImpl" class="library.service.PersonServiceImpl" />
<bean id="bookServiceImpl" class="library.service.BookServiceImpl" />
<!-- Spring Repositories. -->
<bean id="personDAOImpl" class="library.dao.PersonDAOImpl" />
<bean id="bookDAOImpl" class="library.dao.BookDAOImpl" />
<!-- Spring Validators. -->
<bean id="personValidator" class="library.validator.PersonValidator" />
<bean id="bookValidator" class="library.validator.BookValidator" />
<!-- Spring ViewResolver. -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<!-- Spring MesssageSource. -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename">
<value>/WEB-INF/classes/messages</value>
</property>
</bean>
<!-- Spring Properties file for Library. -->
<bean id="propertiesFactory" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location">
<value>classpath:library.properties</value>
</property>
</bean>
<!-- Hibernate DataSource. -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver" />
<!--property name="driverClassName" value="org.apache.derby.jdbc.EmbeddedDriver" /-->
<property name="url" value="jdbc:derby://localhost:1527/Library" />
<property name="username" value="username" />
<property name="password" value="password" />
</bean>
<!-- Hibernate Interceptors. -->
<bean id="serverInterceptor" class="library.interceptor.ServerInterceptor" />
<!-- Hibernate SessionFactory. -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.DerbyDialect</prop>
<!--prop key="hibernate.dialect">org.hibernate.dialect.DerbyTenSixDialect</prop-->
<prop key="hibernate.show_sql">false</prop>
<!-- What to do with the database schema. -->
<prop key="hbm2ddl.auto">validate</prop>
<!-- validate: validate the schema, makes no changes to the database.
update: update the schema.
create: creates the schema, destroying previous data.
create-drop: drop the schema at the end of the session. -->
</props>
</property>
<property name="entityInterceptor">
<ref bean="serverInterceptor" />
</property>
<property name="packagesToScan">
<list>
<value>library.model</value>
</list>
</property>
</bean>
<!-- Hibernate TransactionManagment. -->
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
And the errors given when the application builds and fails in the one environment is:
WARN|01 07 2015|16 26 31|http-nio-8080-exec-73|org.hibernate.engine.jdbc.internal.JdbcServicesImpl| - HHH000342: Could not obtain connection to query metadata : No suitable driver found for jdbc:derby://localhost:1527/Library
INFO|01 07 2015|16 26 31|http-nio-8080-exec-73|org.hibernate.dialect.Dialect| - HHH000400: Using dialect: org.hibernate.dialect.DerbyTenSixDialect
INFO|01 07 2015|16 26 34|http-nio-8080-exec-73|org.hibernate.engine.jdbc.internal.LobCreatorBuilder| - HHH000422: Disabling contextual LOB creation as connection was null
ERROR|01 07 2015|16 26 41|http-nio-8080-exec-73|org.springframework.web.context.ContextLoader| - Context initialization failed
Which is then causing the wiring of the dependencies to fail.
What do these messages mean?
The application is using Spring 4.0.2 with hibernate-core-4.3.10.jar. All dependencies are identical between the three environments and a listing of them follows:
30 Jun 2015 20 26 445,288 antlr-2.7.7.jar
30 Jun 2015 20 26 4,467 aopalliance-1.0.jar
30 Jun 2015 20 26 160,519 commons-dbcp-1.4.jar
30 Jun 2015 20 26 62,050 commons-logging-1.1.3.jar
30 Jun 2015 20 26 2,834,700 derby.jar
30 Jun 2015 20 26 582,639 derbyclient.jar
30 Jun 2015 20 26 313,898 dom4j-1.6.1.jar
30 Jun 2015 20 26 75,311 hibernate-commons-annotations-4.0.4.Final.jar
30 Jun 2015 20 26 5,280,098 hibernate-core-4.3.10.Final.jar
30 Jun 2015 20 27 113,371 hibernate-jpa-2.1-api-1.0.0.Final.jar
30 Jun 2015 20 26 38,605 jackson-annotations-2.4.0.jar
30 Jun 2015 20 26 225,306 jackson-core-2.4.1.jar
30 Jun 2015 20 27 228,552 jackson-core-asl-1.9.7.jar
30 Jun 2015 20 26 1,074,275 jackson-databind-2.4.1.jar
30 Jun 2015 20 26 786,084 jackson-mapper-lgpl-1.9.13.jar
30 Jun 2015 20 26 76,551 jandex-1.1.0.Final.jar
30 Jun 2015 20 26 714,194 javassist-3.18.1-GA.jar
30 Jun 2015 20 26 162,126 javax.persistence-2.1.0.jar
30 Jun 2015 20 26 57,183 jboss-logging-3.1.3.GA.jar
30 Jun 2015 20 26 11,558 jboss-logging-annotations-1.2.0.Beta1.jar
30 Jun 2015 20 27 27,717 jboss-transaction-api_1.2_spec-1.0.0.Final.jar
30 Jun 2015 20 26 20,682 jstl-1.1.2.jar
30 Jun 2015 20 26 15,071 jta-1.1.jar
30 Jun 2015 20 26 367,444 log4j-1.2.14.jar
30 Jun 2015 20 27 52,150 persistence-api-1.0.jar
30 Jun 2015 20 27 36,364 spring-annotation-base-1.0.2.jar
30 Jun 2015 20 26 352,730 spring-aop-4.0.2.RELEASE.jar
30 Jun 2015 20 26 669,044 spring-beans-4.0.2.RELEASE.jar
30 Jun 2015 20 26 974,272 spring-context-4.0.2.RELEASE.jar
30 Jun 2015 20 26 960,994 spring-core-4.0.2.RELEASE.jar
30 Jun 2015 20 26 204,780 spring-expression-4.0.2.RELEASE.jar
30 Jun 2015 20 26 419,614 spring-jdbc-4.0.2.RELEASE.jar
30 Jun 2015 20 26 366,844 spring-orm-4.0.2.RELEASE.jar
30 Jun 2015 20 26 248,204 spring-tx-4.0.2.RELEASE.jar
30 Jun 2015 20 26 665,015 spring-web-4.0.2.RELEASE.jar
30 Jun 2015 20 26 660,329 spring-webmvc-4.0.2.RELEASE.jar
30 Jun 2015 20 26 393,259 standard-1.1.2.jar
It looks like derbyclient.jar is not present in your lib, So please add this jar in your libraries. Download it from here
I think it is about your connection string. Could you try it like this?
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
property name="driverClassName" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="url" value="jdbc:derby:~/Library" />
<property name="username" value="username" />
<property name="password" value="password" />
</bean>
This will create a database named Library on $USER_HOME.
Update
On default derby do not support connection string like jdbc:derby://localhost/Libarary . In order to connect a derby server over network you add derbynet.jar to your class path. You can find additional info here.
Then you can use your default datasource definition.
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.apache.derby.jdbc.ClientDriver" />
<property name="url" value="jdbc:derby://localhost:1527/Library" />
<property name="username" value="username" />
<property name="password" value="password" />
</bean>
Related
My kar file contains the following bundles:
a)common-bundle(contains hibernate as the JPA provider)
b)client-bundle(accesses the entityManagerFactory present inside common-bundle and execute business logic)
I've a strange problem while executing hot deploy of kar file on karaf container.
If I try to do a normal deploy(i.e. by stopping the karaf container,putting the kar file into deploy folder and re-starting karaf container),both the bundles get up and running without any problem.
However,when I try to hot deploy the kar file on karaf container,it throws me the following exception:
Dec 06 13:50:50 INFO 141 HHH000204: Processing PersistenceUnitInfo [
name: MyModelClass
...]
Dec 06 13:50:51 INFO 141 HHH000130: Instantiating explicit connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
Dec 06 13:50:51 ERROR 187 The DataSource osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/ds) required by bundle common-bundle/0.0.1.SNAPSHOT could not be found.
javax.naming.NameNotFoundException: osgi:service/javax.sql.DataSource/"(osgi.jndi.service.name=jdbc/ds)"
at org.apache.aries.jndi.url.ServiceRegistryContext.lookup(ServiceRegistryContext.java:113)[66:org.apache.aries.jndi.url:1.1.0]
at org.apache.aries.jndi.url.ServiceRegistryContext.lookup(ServiceRegistryContext.java:138)[66:org.apache.aries.jndi.url:1.1.0]
at org.apache.aries.jndi.DelegateContext.lookup(DelegateContext.java:161)[64:org.apache.aries.jndi.core:1.0.2]
at javax.naming.InitialContext.lookup(InitialContext.java:417)[:1.8.0_141]
at org.apache.aries.jpa.container.unit.impl.JndiDataSource.getDs(JndiDataSource.java:66)[187:org.apache.aries.jpa.container:1.0.4]
at org.apache.aries.jpa.container.unit.impl.DelayedLookupDataSource.getConnection(DelayedLookupDataSource.java:36)[187:org.apache.aries.jpa.container:1.0.4]
at org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider.getConnection(InjectedDataSourceConnectionProvider.java:70)[213:org.hibernate.entitymanager:4.2.21.Final]
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:242)[212:org.hibernate.core:4.2.21.Final]
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:117)[212:org.hibernate.core:4.2.21.Final]
at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:85)[212:org.hibernate.core:4.2.21.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:184)[212:org.hibernate.core:4.2.21.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:156)[212:org.hibernate.core:4.2.21.Final]
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1827)[212:org.hibernate.core:4.2.21.Final]
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1785)[212:org.hibernate.core:4.2.21.Final]
at org.hibernate.ejb.EntityManagerFactoryImpl.(EntityManagerFactoryImpl.java:96)[213:org.hibernate.entitymanager:4.2.21.Final]
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:915)[213:org.hibernate.entitymanager:4.2.21.Final]
at org.hibernate.osgi.OsgiPersistenceProvider.createContainerEntityManagerFactory(OsgiPersistenceProvider.java:99)[214:org.hibernate.osgi:4.2.21.Final]
at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.createEntityManagerFactories(EntityManagerFactoryManager.java:432)[187:org.apache.aries.jpa.container:1.0.4]
at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.registerEntityManagerFactories(EntityManagerFactoryManager.java:292)[187:org.apache.aries.jpa.container:1.0.4]
at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.access$000(EntityManagerFactoryManager.java:74)[187:org.apache.aries.jpa.container:1.0.4]
at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager$1.call(EntityManagerFactoryManager.java:203)[187:org.apache.aries.jpa.container:1.0.4]
at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager$1.call(EntityManagerFactoryManager.java:199)[187:org.apache.aries.jpa.container:1.0.4]
at java.util.concurrent.FutureTask.run(FutureTask.java:266)[:1.8.0_141]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)[:1.8.0_141]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)[:1.8.0_141]
at java.lang.Thread.run(Thread.java:748)[:1.8.0_141]
Dec 06 13:50:51 WARN 187 Error creating EntityManagerFactory
java.lang.RuntimeException: The DataSource osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/ds) required by bundle common-bundle/0.0.1.SNAPSHOT could not be found.
at org.apache.aries.jpa.container.unit.impl.JndiDataSource.getDs(JndiDataSource.java:87)[187:org.apache.aries.jpa.container:1.0.4]
at org.apache.aries.jpa.container.unit.impl.DelayedLookupDataSource.getConnection(DelayedLookupDataSource.java:36)[187:org.apache.aries.jpa.container:1.0.4]
at org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider.getConnection(InjectedDataSourceConnectionProvider.java:70)[213:org.hibernate.entitymanager:4.2.21.Final]
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:242)[212:org.hibernate.core:4.2.21.Final]
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:117)[212:org.hibernate.core:4.2.21.Final]
at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:85)[212:org.hibernate.core:4.2.21.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:184)[212:org.hibernate.core:4.2.21.Final]
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:156)[212:org.hibernate.core:4.2.21.Final]
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1827)[212:org.hibernate.core:4.2.21.Final]
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1785)[212:org.hibernate.core:4.2.21.Final]
at org.hibernate.ejb.EntityManagerFactoryImpl.(EntityManagerFactoryImpl.java:96)[213:org.hibernate.entitymanager:4.2.21.Final]
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:915)[213:org.hibernate.entitymanager:4.2.21.Final]
at org.hibernate.osgi.OsgiPersistenceProvider.createContainerEntityManagerFactory(OsgiPersistenceProvider.java:99)[214:org.hibernate.osgi:4.2.21.Final]
at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.createEntityManagerFactories(EntityManagerFactoryManager.java:432)[187:org.apache.aries.jpa.container:1.0.4]
at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.registerEntityManagerFactories(EntityManagerFactoryManager.java:292)[187:org.apache.aries.jpa.container:1.0.4]
at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager.access$000(EntityManagerFactoryManager.java:74)[187:org.apache.aries.jpa.container:1.0.4]
at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager$1.call(EntityManagerFactoryManager.java:203)[187:org.apache.aries.jpa.container:1.0.4]
at org.apache.aries.jpa.container.impl.EntityManagerFactoryManager$1.call(EntityManagerFactoryManager.java:199)[187:org.apache.aries.jpa.container:1.0.4]
at java.util.concurrent.FutureTask.run(FutureTask.java:266)[:1.8.0_141]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)[:1.8.0_141]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)[:1.8.0_141]
at java.lang.Thread.run(Thread.java:748)[:1.8.0_141]
Caused by: javax.naming.NameNotFoundException: osgi:service/javax.sql.DataSource/"(osgi.jndi.service.name=jdbc/ds)"
at org.apache.aries.jndi.url.ServiceRegistryContext.lookup(ServiceRegistryContext.java:113)[66:org.apache.aries.jndi.url:1.1.0]
at org.apache.aries.jndi.url.ServiceRegistryContext.lookup(ServiceRegistryContext.java:138)[66:org.apache.aries.jndi.url:1.1.0]
at org.apache.aries.jndi.DelegateContext.lookup(DelegateContext.java:161)[64:org.apache.aries.jndi.core:1.0.2]
at javax.naming.InitialContext.lookup(InitialContext.java:417)[:1.8.0_141]
at org.apache.aries.jpa.container.unit.impl.JndiDataSource.getDs(JndiDataSource.java:66)[187:org.apache.aries.jpa.container:1.0.4]
... 21 more
Dec 06 13:50:51 INFO 141 HHH000204: Processing PersistenceUnitInfo [
name: MyModelClass
...]
Dec 06 13:50:52 INFO 141 HHH000130: Instantiating explicit connection provider: org.hibernate.ejb.connection.InjectedDataSourceConnectionProvider
Dec 06 13:50:55 INFO 141 HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
Dec 06 13:50:55 INFO 141 HHH000268: Transaction strategy: org.hibernate.engine.transaction.internal.jdbc.JdbcTransactionFactory
Dec 06 13:50:55 INFO 141 HHH000397: Using ASTQueryTranslatorFactory
Dec 06 13:50:56 WARN 141 HHH000008: JTASessionContext being used with JDBCTransactionFactory; auto-flush will not operate correctly with getCurrentSession()
Following are the most important contents of the bundles:
common-bundle:
Persistence.xml:
<persistence version="2.0"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="my-persistent-unit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<non-jta-data-source>osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/ds)</non-jta-data-source>
<class>MyModelClass</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
</persistence-unit>
blueprint.xml:
<cm:property-placeholder persistent-id='my-persistent-id'
update-strategy='reload'
placeholder-prefix="${"
placeholder-suffix="}">
<cm:default-properties>
<cm:property name="driver" value="undefined"/>
<cm:property name="url" value="undefined"/>
<cm:property name="username" value="undefined"/>
<cm:property name="password" value="undefined"/>
</cm:default-properties>
</cm:property-placeholder>
<jasypt:property-placeholder encryptor-ref="encryptor"/>
<reference id="encryptor" interface="org.jasypt.encryption.StringEncryptor" availability="mandatory"/>
<bean id='myDs'
class="CustomConnection">
<property name="connectionFactoryClassName" value="oracle.jdbc.pool.OracleDataSource"/>
<property name="URL" value="${url}"/>
<property name="user" value="${username}"/>
<property name="password" value="${password}"/>
<property name="validateConnectionOnBorrow" value="true"/>
</bean>
<service ref='myDs' interface='javax.sql.DataSource'>
<service-properties>
<entry key='osgi.jndi.service.name' value='jdbc/ds'/>
</service-properties>
</service>
client-bundle:
blueprint.xml
<bean id="myController"
class="MyController">
<argument ref="entityManagerFactory"/>
</bean>
<reference id="entityManagerFactory"
interface="javax.persistence.EntityManagerFactory"
filter="(osgi.unit.name=my-persistent-unit)"
availability="mandatory"/>
Please help.
Apparently every bundle is using a datasource but no one is creating it.
javax.naming.NameNotFoundException: osgi:service/javax.sql.DataSource/"(osgi.jndi.service.name=jdbc/ds)"
You need to create this datasource, for example by dropping a simple XML file into deploy dir:
<?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/yourdb"/>
<property name="username" value="XXX"/>
<property name="password" value="XXX"/>
</bean>
<service interface="javax.sql.DataSource" ref="dataSource">
<service-properties>
<entry key="osgi.jndi.service.name" value="jdbc/ds"/>
</service-properties>
</service>
</blueprint>
You will need jdbc and jndi features installed.
Couldn't find what is wrong with inserting data in mySQL database using Spring data, JPA, hibernate and mySQL. It is inserting data twice in database.
The root-context.xml file is:
<?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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.8.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
<!-- Root Context: defines shared resources visible to all other web components -->
<context:component-scan base-package="com.project.db">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<jdbc:embedded-database type="HSQL" id="dataSource"/>
<!-- <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost/jpa"/>
<property name="username" value="root"/>
<property name="password" value=""/>
</bean> -->
<!-- <bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="MYSQL"/>
</bean> -->
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
id="entityManagerFactory">
<property name="packagesToScan" value="com.project.db.entity"></property>
<property name="dataSource" ref="dataSource"></property>
<!-- <property name="jpaVendorAdapter" ref="jpaVendorAdapter"/> -->
<property name="jpaProperties">
<props>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">create</prop>
</props>
</property>
<property name="persistenceProvider">
<bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean class="org.springframework.orm.jpa.JpaTransactionManager"
id="transactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<jpa:repositories base-package="com.project.db.repository"/>
</beans>
The servlet-context.xml file is:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.project.db" />
</beans:beans>
My #Entity class is:
#Entity
public class User {
#Id
#GeneratedValue
private Integer id ;
private String name ;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
JPA repository is:
import org.springframework.data.jpa.repository.JpaRepository;
import com.project.entity.User;
public interface UserRepository extends JpaRepository<User, Integer> {
}
And, finally, #Service class is:
import javax.annotation.PostConstruct;
import javax.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.project.entity.User;
import com.project.repository.UserRepository;
#Transactional
#Service
public class InitDbService {
#Autowired
private UserRepository userRepository;
#PostConstruct
public void init() {
User user = new User();
user.setName("Ali");
userRepository.save(user);
}
}
The above code works without errors/exceptions; database/table is also created but data is inserted into Entity/table twice when I see that in mySQL database.
Project is at github.
Console output is:
INFO: Spring WebApplicationInitializers detected on classpath: [com.project.db.WebAppInitializer#1867584]
Sep 2, 2015 12:50:17 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Wed Sep 02 12:50:17 PKT 2015]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/root-context.xml]
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
Hibernate: drop table if exists users
Hibernate: create table users (id integer not null auto_increment, name varchar(255), primary key (id))
Hibernate: insert into users (name) values (?) // first time inserting here and
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 5633 ms
Sep 2, 2015 12:50:23 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'springDispatcher'
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'springDispatcher': initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing WebApplicationContext for namespace 'springDispatcher-servlet': startup date [Wed Sep 02 12:50:23 PKT 2015]; parent: Root WebApplicationContext
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String com.project.db.HomeController.home(java.util.Locale,org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - Looking for #ControllerAdvice: WebApplicationContext for namespace 'springDispatcher-servlet': startup date [Wed Sep 02 12:50:23 PKT 2015]; parent: Root WebApplicationContext
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter - Looking for #ControllerAdvice: WebApplicationContext for namespace 'springDispatcher-servlet': startup date [Wed Sep 02 12:50:23 PKT 2015]; parent: Root WebApplicationContext
INFO : org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/resources/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0'
Hibernate: insert into users (name) values (?) // Second time inserting here
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'springDispatcher': initialization completed in 1483 ms
Sep 2, 2015 12:50:25 PM org.apache.catalina.core.StandardContext reload
INFO: Reloading Context with name [/db] is completed
Taking a chance here since I see that you are using Spring MVC.
With Spring MVC, you have a servlet-context which defines the controllers, and an applicationContext for other beans. It might be that you are scanning for beans other than controllers in the servlet-context, which in turn will give you two beans of InitDbService, both running their #PostConstruct-method, inserting into the database.
This can be solved by defining component-scan like this:
servlet-context (after placing controllers and controllers only in a separate package):
<context:component-scan base-package="com.my.project.controller" />
applicationContext:
<context:component-scan base-package="com.my.project">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
You have to enable DEBUG logging to check that your initailizing bean isn't created twice, as Tobb mentioned before your bean is probabbly created in both contexts. Log stands clearly that first insert is executed during root context initialization (witch is correct) and second time during servlet context initialization (which is wrong)
I have found solution to your problem: You have to add commponent scan without default filters to your root-context
<context:component-scan base-package="com.project.db" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
</context:component-scan>
and servlet-context is
<context:component-scan base-package="com.project.db" />
I have tested your project and its working fine with this change.
I am working on a messy web java project, with hibernate and tomcat server. First time i deploy the war on the server i can see the following log:
...
ContextLoader:273 - Root WebApplicationContext: initialization started XmlWebApplicationContext:495 - Refreshing Root WebApplicationContext: startup date [Wed Aug 06 14:18:37 COT 2014]; root of context hierarchy
XmlBeanDefinitionReader:315 - Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml]
DefaultListableBeanFactory:557 - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#4fba4e8c: defining beans [dataSource,sessionFactory,jdbcExceptionTranslator,hibernateTemplate,transactionManager,AbstractSpringDao,.......]; root of factory hierarchy
Environment:514 - Hibernate 3.2.5
Environment:547 - hibernate.properties not found
Environment:681 - Bytecode provider name : cglib
Environment:598 - using JDK 1.4 java.sql.Timestamp handling
HbmBinder:300 - Mapping class: co.com...bean1...
HbmBinder:300 - Mapping class: co.com...bean2...
HbmBinder:300 - Mapping class: co.com...bean3...
HbmBinder:300 - Mapping class: co.com...bean4...
...
but every time i open the home page on a new browser window.... i see this log:
FileSystemXmlApplicationContext:495 - Refreshing org.springframework.context.support.FileSystemXmlApplicationContext#4f8e9bee: startup date [Wed Aug 06 14:40:30 COT 2014]; root of context hierarchy
XmlBeanDefinitionReader:315 - Loading XML bean definitions from file [/home/david/Documents/INTERKONT/siccu/siente/build/web/WEB-INF/applicationContext.xml]
DefaultListableBeanFactory:557 - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#6b8616ff: defining beans [dataSource,sessionFactory,jdbcExceptionTranslator,hibernateTemplate,transactionManager,AbstractSpringDao .......]; root of factory hierarchy
HbmBinder:300 - Mapping class: co.com....bean1...
HbmBinder:300 - Mapping class: co.com....bean2...
HbmBinder:300 - Mapping class: co.com....bean3...
...
Any ideas????
this is my applicationContext.xml
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">
<!-- DataSource Definition -->
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName">
<value>org.postgresql.Driver</value>
</property>
<property name="url">
<value>jdbc:postgresql:DBDBDBDBDB</value>
</property>
<property name="username">
<value>XXXX</value>
</property>
<property name="password">
<value>YYYYYYYY</value>
</property>
</bean>
<!-- Hibernate SessionFactory Definition -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="mappingResources">
<list>
<value>co/com/....bean1.hbm.xml</value>
<value>co/com/....bean2.hbm.xml</value>
<value>co/com/....bean3.hbm.xml</value>
...
...
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.bytecode.use_reflection_optimizer">false</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
</props>
</property>
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
<!-- Spring Data Access Exception Translator Defintion -->
<bean id="jdbcExceptionTranslator"
class="org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator">
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
<!-- Hibernate Template Defintion -->
<bean id="hibernateTemplate"
class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
<property name="jdbcExceptionTranslator">
<ref bean="jdbcExceptionTranslator" />
</property>
</bean><!-- Hibernate Transaction Manager Definition -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<bean id="AbstractSpringDao" abstract="true" class="cobra.dao.AbstractSpringDao" scope="prototype">
<property name="hibernateTemplate">
<ref bean="hibernateTemplate" />
</property>
</bean>
...
...
it seems you are creating application context in your controller.
move this code outside of the controller.
ApplicationContext ctx = new FileSystemXmlApplicationContext("WEB-INF/applicationContext.xml");
and configure in your web.xml similer to below
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
In the first block off log lines, you see the correct way to configure spring in a web application: the context is loaded through the ContextLoader either from a listener or from a (Dispatcher)Servlet.
In the second block, the same application context is loaded again directly from disk. This is not correct.
The second load probably happens in a Servlet.service(...) method.
Instead of reloading the application context on every request, you could use WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()); to access the one loaded previously.
This is not the preferred way to use spring in a web application (You should read about spring web), but it is probably the easiest way to fix your setup.
We're trying to set a re-delivery policy for ActiveMQ using spring jms. We've set an exponential back-off for the re-deliveries, but it seems to be ignored - the intervals between the message re-deliveries are fixed instead of exponentially growing.
Does anyone know what might be the problem? This is our spring-jms configuration:
<bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory"
p:brokerURL="${activemq_url}">
<property name="redeliveryPolicy" ref="redeliveryPolicy" />
</bean>
<bean id="redeliveryPolicy" class="org.apache.activemq.RedeliveryPolicy">
<property name="queue" value="*" />
<property name="initialRedeliveryDelay" value="10000" />
<property name="redeliveryDelay" value="10000" />
<property name="maximumRedeliveries" value="-1" />
<property name="useExponentialBackOff" value="true" />
<property name="backOffMultiplier" value="5" />
</bean>
<bean id="cachingConnectionFactory" class="org.springframework.jms.connection.CachingConnectionFactory"
p:targetConnectionFactory-ref="connectionFactory" p:sessionCacheSize="10"
/>
<!-- A JmsTemplate instance that uses the cached connection and destination -->
<bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
<property name="connectionFactory" ref="cachingConnectionFactory" />
<property name="messageConverter" ref="messageConverter" />
<property name="sessionTransacted" value="true" />
</bean>
<!-- The Spring message listener container configuration -->
<jms:listener-container container-type="default"
destination-type="queue" connection-factory="connectionFactory"
acknowledge="transacted" concurrency="1" cache="consumer">
<jms:listener destination="testQueue" ref="testService"
method="onMessage" />
</jms:listener-container>
Thanks!
EDIT: This is a log example, the re-deliveries happen every 5 seconds:
11 May 2014 18:52:00 WARN DefaultMessageListenerContainer - Execution of JMS message listener failed, and no ErrorHandler has been set.
javax.jms.JMSException: Sun May 11 18:52:00 IDT 2014
at ...
11 May 2014 18:52:05 WARN DefaultMessageListenerContainer - Execution of JMS message listener failed, and no ErrorHandler has been set.
javax.jms.JMSException: Sun May 11 18:52:05 IDT 2014
at ...
11 May 2014 18:52:10 WARN DefaultMessageListenerContainer - Execution of JMS message listener failed, and no ErrorHandler has been set.
javax.jms.JMSException: Sun May 11 18:52:10 IDT 2014
at ...
11 May 2014 18:52:15 WARN DefaultMessageListenerContainer - Execution of JMS message listener failed, and no ErrorHandler has been set.
javax.jms.JMSException: Sun May 11 18:52:15 IDT 2014
at ...
11 May 2014 18:52:20 WARN DefaultMessageListenerContainer - Execution of JMS message listener failed, and no ErrorHandler has been set.
javax.jms.JMSException: Sun May 11 18:52:20 IDT 2014
at ...
So, I think I found the problem:
When I was testing the policy before, I threw JMSException to get the messages to be re-delivered.
One I changed the exception that was thrown to Exception/RuntimeException, the exponential back off worked.
I'm not sure why JMSException causes the exponential back off policy to be ignored...Does anyone have any ideas?
When I start SpringMVC, I get the following exception...
Apr 28, 2012 6:08:23 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /usr/bin/jdk1.7.0_03/jre/lib/amd64/server:/usr/bin/jdk1.7.0_03/jre/lib/amd64:/usr/bin/jdk1.7.0_03/jre/../lib/amd64:/usr/lib/jvm/java-6-openjdk/jre/lib/amd64/server:/usr/lib/jvm/java-6-openjdk/jre/lib/amd64:/usr/lib/jvm/java-6-openjdk/jre/../lib/amd64:/usr/java/packages/lib/amd64:/usr/lib64:/lib64:/lib:/usr/lib
Apr 28, 2012 6:08:23 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server:spring-security-integration' did not find a matching property.
Apr 28, 2012 6:08:23 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:Spring3Hibernate' did not find a matching property.
Apr 28, 2012 6:08:23 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:assessment' did not find a matching property.
Apr 28, 2012 6:08:24 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Apr 28, 2012 6:08:24 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Apr 28, 2012 6:08:24 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 601 ms
Apr 28, 2012 6:08:24 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Apr 28, 2012 6:08:24 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.26
Apr 28, 2012 6:08:24 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Sat Apr 28 18:08:24 BST 2012]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/root-context.xml]
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#1c56295f: defining beans []; root of factory hierarchy
INFO : org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 234 ms
Apr 28, 2012 6:08:24 PM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'appServlet'
INFO : org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'appServlet': initialization started
INFO : org.springframework.web.context.support.XmlWebApplicationContext - Refreshing WebApplicationContext for namespace 'appServlet-servlet': startup date [Sat Apr 28 18:08:24 BST 2012]; parent: Root WebApplicationContext
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring/appServlet/servlet-context.xml]
INFO : org.springframework.context.annotation.ClassPathBeanDefinitionScanner - JSR-330 'javax.inject.Named' annotation found and supported for component scanning
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#768404fd: defining beans [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#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.resource.ResourceHttpRequestHandler#0,org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#0,org.springframework.web.servlet.view.InternalResourceViewResolver#0,dataSource,sessionFactory,homeController,userManagementController,userDao,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.view.ContentNegotiatingViewResolver#0,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory#1c56295f
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.String org.assessme.com.HomeController.home(java.util.Locale,org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/userManagement/],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public java.lang.Object org.assessme.com.UserManagementController.home(java.util.Locale,org.springframework.ui.Model)
INFO : org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped "{[/userManagement/getUser],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}" onto public org.assessme.com.entity.User org.assessme.com.UserManagementController.data(java.util.Locale,org.springframework.ui.Model)
INFO : org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/resources/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0'
ERROR: org.hibernate.tool.hbm2ddl.SchemaUpdate - could not get database metadata
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown table 'sequences' in information_schema
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2618)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568)
at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1557)
at org.apache.commons.dbcp.DelegatingStatement.executeQuery(DelegatingStatement.java:208)
at org.apache.commons.dbcp.DelegatingStatement.executeQuery(DelegatingStatement.java:208)
at org.hibernate.tool.hbm2ddl.DatabaseMetadata.initSequences(DatabaseMetadata.java:151)
at org.hibernate.tool.hbm2ddl.DatabaseMetadata.<init>(DatabaseMetadata.java:69)
at org.hibernate.tool.hbm2ddl.DatabaseMetadata.<init>(DatabaseMetadata.java:62)
at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:170)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:386)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1385)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:954)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory(LocalSessionFactoryBean.java:860)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:779)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1514)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)
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.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:631)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:588)
at org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:645)
at org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:508)
at org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:449)
at org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:133)
at javax.servlet.GenericServlet.init(GenericServlet.java:160)
at org.apache.catalina.core.StandardWrapper.initServlet(StandardWrapper.java:1266)
at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1185)
at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:1080)
at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:5015)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5302)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1566)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1556)
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:722)
The important detail appears to be in ERROR: org.hibernate.tool.hbm2ddl.SchemaUpdate - could not get database metadata
My servlet-context.xml is as follows...
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost/assessme" />
<beans:property name="username" value="root" />
<beans:property name="password" value="toor" />
</beans:bean>
<beans:bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<beans:property name="annotatedClasses">
<beans:list>
<beans:value>org.assessme.com.entity.User</beans:value>
</beans:list>
</beans:property>
<beans:property name="dataSource" ref="dataSource" />
<beans:property name="packagesToScan" value="data" />
<beans:property name="hibernateProperties">
<beans:props>
<beans:prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</beans:prop>
<beans:prop key="hibernate.current_session_context_class">thread</beans:prop>
<beans:prop key="hibernate.transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</beans:prop>
<beans:prop key="hibernate.show_sql">true</beans:prop>
<beans:prop key="hibernate.hbm2ddl.auto">update</beans:prop>
</beans:props>
</beans:property>
</beans:bean>
<context:component-scan base-package="org.assessme.com" />
<beans:bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<beans:property name="mediaTypes">
<beans:map>
<beans:entry key="html" value="text/html" />
<beans:entry key="json" value="application/json" />
</beans:map>
</beans:property>
<beans:property name="defaultViews">
<beans:list>
<beans:bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<beans:property name="prefixJson" value="true" />
</beans:bean>
</beans:list>
</beans:property>
</beans:bean>
</beans:beans>
I'm certain the url details and credentials are correct for the database, can anyone think of any other reasons?
It looks like it's trying to access the information_schema db, but in my XML I have set the db it should look at...
<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
<beans:property name="url" value="jdbc:mysql://localhost/assessme" />
<beans:property name="username" value="root" />
<beans:property name="password" value="toor" />
</beans:bean>
Thanks,
David
I'm extracting the correct answer to this question from the comments of a different answer.
This Exception gets thrown because your used dialect doesn't match the database.
In your configuration you use
<beans:prop key="hibernate.dialect">org.hibernate.dialect.H2Dialect</beans:prop>
although you're accessing a MySQL database. You should use a MySQL dialect instead. E.g.
<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</beans:prop>
Look at your error:
ERROR: org.hibernate.tool.hbm2ddl.SchemaUpdate - could not get database metadata
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown table 'sequences' in information_schema
You are mapping your MySQL to information_schema which is system database in MySQL and this database does not contain sequances table,
BTW, of the record, you need to take into consideration that MySQL does not have "CREATE Sequance" command.
let you add this in the application.properties file
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
the the error will be disappeared.