Spring Hibernate Exception - java

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.

Related

Spring MVC Controller mapping does not work

I am working on a spring-mvc project. After many tries, I am unable to the map the controller in spring. As a result, the below url always returns as 404 not found.
http://localhost:8080/EcommerceBookStore/rest/welcome
Here is the web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>EcommerceBookStore</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml,
/WEB-INF/Ecommerce-servlet.xml
</param-value>
</context-param>
<servlet>
<servlet-name>Ecommerce</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Ecommerce</servlet-name>
<url-pattern>/rest/</url-pattern>
</servlet-mapping>
<!-- <servlet>
<servlet-name>Ecommerce</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.java.Client</param-name>
<param-value>com.java.Client</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>-->
</web-app>
Here is the Ecommerce-servlet.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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<mvc:default-servlet-handler/>
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean class="org.springframework.security.web.bind.support.AuthenticationPrincipalArgumentResolver" />
</mvc:argument-resolvers>
</mvc:annotation-driven>
<!-- bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WebContent" />
<property name="suffix" value=".jsp" />
</bean-->
<bean id="viewResolver"
class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<mvc:annotation-driven />
<context:component-scan base-package="com.webspider"/>
<mvc:resources mapping="/Resources/**" location="/Resources/" />
</beans>
Here is the
<?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:security="http://www.springframework.org/schema/security"
xmlns:webflow-config="http://www.springframework.org/schema/webflow-config"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd http://www.springframework.org/schema/webflow-config http://www.springframework.org/schema/webflow-config/spring-webflow-config.xsd">
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"
id="dataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/Ecommerce"></property>
<property name="username" value="root"></property>
<property name="password" value="pass"></property>
</bean>
<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.MySQL5Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.webspider</value>
</list>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="10240000" />
</bean>
<security:http auto-config="true">
<security:intercept-url pattern="/admin/**" access="ROLE_ADMIN" />
<security:intercept-url pattern="/customer/**" access="ROLE_USER" />
<security:form-login
login-page="/login"
default-target-url="/product/productList"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password" />
<security:logout
logout-success-url="/login?logout" />
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:jdbc-user-service
data-source-ref="dataSource"
authorities-by-username-query="SELECT username, authority FROM authorities WHERE username = ?"
users-by-username-query="SELECT username, password, enabled FROM users WHERE username = ?" />
</security:authentication-provider>
</security:authentication-manager>
<webflow-config:flow-executor id="flowExecutor" flow-registry="flowRegistry" />
<webflow-config:flow-registry id="flowRegistry" base-path="/WEB-INF/flows">
<webflow-config:flow-location path="/checkout/checkout-flow.xml" id="checkout" />
</webflow-config:flow-registry>
<bean id="flowHandlerMapping" class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping">
<property name="flowRegistry" ref="flowRegistry" />
</bean>
<bean id="flowHandlerAdapter" class="org.springframework.webflow.mvc.servlet.FlowHandlerAdapter">
<property name="flowExecutor" ref="flowExecutor" />
</bean>
</beans>
Here is the helloworld controller
package com.webspider.Controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/*
* author: Crunchify.com
*
*/
#Controller
public class HelloWorld {
#RequestMapping("/welcome")
public ModelAndView helloWorld() {
String message = "<br><div style='text-align:center;'>"
+ "<h3>********** Hello World, Spring MVC Tutorial</h3>This message is coming from CrunchifyHelloWorld.java **********</div><br><br>";
return new ModelAndView("welcome", "message", message);
}
}
Here is the tomcat output
Nov 23, 2016 12:41:14 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=UTF-8
Nov 23, 2016 12:41:14 AM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /Users/atishpatra/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.
Nov 23, 2016 12:41:15 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Nov 23, 2016 12:41:15 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Nov 23, 2016 12:41:15 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Nov 23, 2016 12:41:15 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Nov 23, 2016 12:41:15 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 972 ms
Nov 23, 2016 12:41:15 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Nov 23, 2016 12:41:15 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.38
Nov 23, 2016 12:41:18 AM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Nov 23, 2016 12:41:18 AM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Nov 23, 2016 12:41:18 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'Ecommerce'
Nov 23, 2016 12:41:18 AM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'Ecommerce': initialization started
Nov 23, 2016 12:41:18 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'Ecommerce-servlet': startup date [Wed Nov 23 00:41:18 CST 2016]; root of context hierarchy
Nov 23, 2016 12:41:18 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/Ecommerce-servlet.xml]
Nov 23, 2016 12:41:19 AM org.springframework.beans.factory.support.DefaultListableBeanFactory registerBeanDefinition
INFO: Overriding bean definition for bean 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping' with a different definition: replacing [Root bean: class [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Root bean: class [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
Nov 23, 2016 12:41:19 AM org.springframework.beans.factory.support.DefaultListableBeanFactory registerBeanDefinition
INFO: Overriding bean definition for bean 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter' with a different definition: replacing [Root bean: class [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Root bean: class [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
Nov 23, 2016 12:41:19 AM org.springframework.beans.factory.support.DefaultListableBeanFactory registerBeanDefinition
INFO: Overriding bean definition for bean 'mvcUriComponentsContributor' with a different definition: replacing [Root bean: class [org.springframework.web.servlet.config.AnnotationDrivenBeanDefinitionParser$CompositeUriComponentsContributorFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Root bean: class [org.springframework.web.servlet.config.AnnotationDrivenBeanDefinitionParser$CompositeUriComponentsContributorFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
Nov 23, 2016 12:41:19 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/**] onto handler 'org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler#0'
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Nov 23, 2016 12:41:20 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: WebApplicationContext for namespace 'Ecommerce-servlet': startup date [Wed Nov 23 00:41:18 CST 2016]; root of context hierarchy
Nov 23, 2016 12:41:20 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for #ControllerAdvice: WebApplicationContext for namespace 'Ecommerce-servlet': startup date [Wed Nov 23 00:41:18 CST 2016]; root of context hierarchy
Nov 23, 2016 12:41:20 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/Resources/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0'
Nov 23, 2016 12:41:20 AM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'Ecommerce': initialization completed in 2089 ms
Nov 23, 2016 12:41:21 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Nov 23, 2016 12:41:21 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Nov 23, 2016 12:41:21 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 5855 ms
I dont see any error in tomcat output. I expected something similar to appear
INFO: Mapped URL path [/welcome] onto handler HelloWorld.
I have no clue what's wrong. Can anyone please point out what I am missing ?
Thanks in advance.
I think you have mixed here:
If your project name is rest and you are deploying it as rest.war then you don't need this line in web.xml
<url-pattern>/rest/</url-pattern>
change it to
<url-pattern>/</url-pattern>
but if you are running it with ROOT.war and you want /rest in url then you have to do as below:
#Controller
#RequestMapping("/rest")
public class HelloWorld {
and then access with below url:
localhost:8080//rest/welcome
Try following,
#RequestMapping("/welcome", method = RequestMethod.GET)
public ModelAndView helloWorld() {...
Make sure your mapping is,
<servlet-mapping>
<servlet-name>Ecommerce</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Customize your default servlet name as,
<mvc:default-servlet-handler default-servlet-name="Ecommerce"/>
URL to try : localhost:8080/Ecommerce/welcome

Deploy Spring MVC 3 Rest on WebSphere Application Server 8

I am trying to deploy a Spring 3 MVC Rest Application on WebSphere Application Server 8.0 and have not had any success.
Here is my controller class
`
#Controller
public class BookingService {
public BookingService() {
System.out.println("test");
}
#RequestMapping(value="/test", method=RequestMethod.GET, produces="application/xml")
#ResponseBody
public String test() {
return "<test>test</test>";
}
}
`
web.xml - servlet spec 3
`
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
</web-app>
`
dispatcher-servlet.xml
`
<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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<mvc:annotation-driven />
<context:component-scan base-package="com.example" />
<!-- <tx:annotation-driven /> -->
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean id="viewResolver" class=
"org.springframework.web.servlet.view.BeanNameViewResolver" />
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="mediaTypes">
<map>
<entry key="html" value="text/html" />
<entry key="json" value="application/json" />
<entry key="json" value="application/xml" />
</map>
</property>
<property name="viewResolvers">
<list>
<bean class="org.springframework.web.servlet.view.UrlBasedViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
</list>
</property>
<property name="defaultViews">
<list>
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
<property name="prefixJson" value="true" />
</bean>
</list>
</property>
</bean>
</beans>
`
I confirm that it does work on tomcat. In the tomcat logs the mapping is being created.
INFO: Mapped "{[/test],methods=[GET],params=[],headers=[],consumes=[],produces=[application/xml],custom=[]}" onto public java.lang.String com.westjet.ens.services.BookingService.test()
Doing a curl on http://localhost:8080/ens-das-web/api/test returns HTTP 200.
However in the was logs this does not appear and doing a curl http://localhost:9080/my-service-web/api/test returns 404 and the following response.
`
Error 404: SRVE0295E: Error reported: 404
`
Also the WAS Log shows the following when doing a curl.
[9/23/15 15:53:21:390 MDT] 00000089 PageNotFound W org.springframework.web.servlet.DispatcherServlet noHandlerFound No mapping found for HTTP request with URI [/ens-das-web/api/test] in DispatcherServlet with name 'dispatcher'
WAS logs:
[9/23/15 15:20:52:809 MDT] 00000049 WASSessionCor I SessionContextRegistry getSessionContext SESN0176I: Will create a new session context for application key default_host/ens-das-web
[9/23/15 15:20:58:993 MDT] 00000049 webapp I com.ibm.ws.webcontainer.webapp.WebApp log SRVE0292I: Servlet Message - [ens-das-web-0_1_war#ens-das-web-0.1.war]:.No Spring WebApplicationInitializer types detected on classpath
[9/23/15 15:20:59:176 MDT] 00000049 webapp I com.ibm.ws.webcontainer.webapp.WebApp log SRVE0292I: Servlet Message - [ens-das-web-0_1_war#ens-das-web-0.1.war]:.Initializing Spring FrameworkServlet 'dispatcher'
[9/23/15 15:20:59:178 MDT] 00000049 DispatcherSer I org.springframework.web.servlet.FrameworkServlet initServletBean FrameworkServlet 'dispatcher': initialization started
[9/23/15 15:20:59:229 MDT] 00000049 XmlWebApplica I org.springframework.context.support.AbstractApplicationContext prepareRefresh Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Wed Sep 23 15:20:59 MDT 2015]; root of context hierarchy
[9/23/15 15:20:59:313 MDT] 00000049 XmlBeanDefini I org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions Loading XML bean definitions from ServletContext resource [/WEB-INF/dispatcher-servlet.xml]
[9/23/15 15:20:59:749 MDT] 00000049 AutowiredAnno I org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor <init> JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
[9/23/15 15:20:59:770 MDT] 00000049 DefaultListab I org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#3c2306c: defining beans [mvcContentNegotiationManager,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.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping#0,org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter#0,viewResolver,org.springframework.web.servlet.view.ContentNegotiatingViewResolver#0,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
[9/23/15 15:21:00:615 MDT] 00000049 DispatcherSer I org.springframework.web.servlet.FrameworkServlet initServletBean FrameworkServlet 'dispatcher': initialization completed in 1436 ms
[9/23/15 15:21:00:615 MDT] 00000049 servlet I com.ibm.ws.webcontainer.servlet.ServletWrapper init SRVE0242I: [ens-das-web-0_1_war] [/ens-das-web] [dispatcher]: Initialization successful.
[9/23/15 15:21:00:616 MDT] 00000049 webcontainer I com.ibm.ws.webcontainer.VirtualHostImpl addWebApplication SRVE0250I: Web Module ENS Data Access Service has been bound to default_host[*:9080,*:80,*:9443,*:5060,*:5061,*:443].
Any help would be much appreciated.
I was able to fix this. For some reason maven was not cleaning the WEB-INF/classes folder and my #Controller class was not available.

Data is inserted twice in database jpa/hibernate

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.

Hibernate cannot find suitable driver for Derby in Spring MVC webapp

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>

Configured SessionFactory: null

I have created basic hibernate application. It throw error message.
Error is:
Oct 18, 2012 3:36:13 PM org.hibernate.cfg.Environment <clinit>
INFO: Hibernate 3.2.5
Oct 18, 2012 3:36:13 PM org.hibernate.cfg.Environment <clinit>
INFO: hibernate.properties not found
Oct 18, 2012 3:36:13 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: Bytecode provider name : cglib
Oct 18, 2012 3:36:13 PM org.hibernate.cfg.Environment <clinit>
INFO: using JDK 1.4 java.sql.Timestamp handling
Oct 18, 2012 3:36:13 PM org.hibernate.cfg.Configuration configure
INFO: configuring from resource: /hibernate.cfg.xml
Oct 18, 2012 3:36:13 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: Configuration resource: /hibernate.cfg.xml
Oct 18, 2012 3:36:13 PM org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : com/crmcall/entity/CallUsers.hbm.xml
Oct 18, 2012 3:36:13 PM org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: com.crmcall.entity.CallUsers -> crmcallusers
Oct 18, 2012 3:36:13 PM org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : com/crmcall/entity/Customers.hbm.xml
Oct 18, 2012 3:36:14 PM org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: com.crmcall.entity.Customers -> crmcustomermaster
Oct 18, 2012 3:36:14 PM org.hibernate.cfg.Configuration addResource
INFO: Reading mappings from resource : com/crmcall/entity/User.hbm.xml
Oct 18, 2012 3:36:14 PM org.hibernate.cfg.HbmBinder bindRootPersistentClassCommonValues
INFO: Mapping class: com.crmcall.entity.User -> crmusers
Oct 18, 2012 3:36:14 PM org.hibernate.cfg.Configuration doConfigure
INFO: Configured SessionFactory: null
Initial SessionFactory creation failed.org.hibernate.MappingException: component class not found: string
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.crmcall.util.HibernateUtil.<clinit>(HibernateUtil.java:27)
at com.crmcall.dao.UserDAO.<init>(UserDAO.java:23)
at com.crmcall.dao.UserDAO.main(UserDAO.java:36)
Caused by: org.hibernate.MappingException: component class not found: string
at org.hibernate.mapping.Component.getComponentClass(Component.java:104)
at org.hibernate.tuple.component.PojoComponentTuplizer.buildGetter(PojoComponentTuplizer.java:133)
at org.hibernate.tuple.component.AbstractComponentTuplizer.<init>(AbstractComponentTuplizer.java:43)
at org.hibernate.tuple.component.PojoComponentTuplizer.<init>(PojoComponentTuplizer.java:38)
at org.hibernate.tuple.component.ComponentEntityModeToTuplizerMapping.<init>(ComponentEntityModeToTuplizerMapping.java:52)
at org.hibernate.tuple.component.ComponentMetamodel.<init>(ComponentMetamodel.java:50)
at org.hibernate.mapping.Component.buildType(Component.java:152)
at org.hibernate.mapping.Component.getType(Component.java:145)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:253)
at org.hibernate.mapping.RootClass.validate(RootClass.java:193)
at org.hibernate.cfg.Configuration.validate(Configuration.java:1102)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1287)
at com.crmcall.util.HibernateUtil.<clinit>(HibernateUtil.java:24)
... 2 more
Caused by: java.lang.ClassNotFoundException: string
at java.net.URLClassLoader$1.run(URLClassLoader.java:200)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at org.hibernate.util.ReflectHelper.classForName(ReflectHelper.java:100)
at org.hibernate.mapping.Component.getComponentClass(Component.java:101)
This is my Hibernate.cfg.xml file:
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.1.5:3306/crmtest</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Enable Hibernate 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>
<mapping resource="com/crmcall/entity/CallUsers.hbm.xml"/>
<mapping resource="com/crmcall/entity/Customers.hbm.xml"/>
<mapping resource="com/crmcall/entity/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
This is my User.hbm.xml
<hibernate-mapping>
<class name="com.crmcall.entity.User" table="crmusers">
<composite-id name="userPK" >
<key-property name="businessUnit" column="BusinessUnit" type="string"/>
<key-property name="userID" column="UserID" type="string"/>
</composite-id>
<property name="recID" >
<column name="RecID"/>
</property>
<property name="password">
<column name="Password"/>
</property>
<property name="userName">
<column name="UserName"/>
</property>
<property name="userType">
<column name="UserType"/>
</property>
<property name="userLevel">
<column name="UserLevel"/>
</property>
<property name="customerCode">
<column name="CustomerCode"/>
</property>
<property name="customerCodeson">
<column name="CustomerCodeson"/>
</property>
<property name="locationCode">
<column name="LocationCode"/>
</property>
<property name="lastUpdatedBy">
<column name="LastUpdatedBy"/>
</property>
<property name="lastUpdatedOn" type="timestamp">
<column name="LastUpdatedOn"/>
</property>
<property name="email" type="string">
<column name="Email"/>
</property>
</class>
</hibernate-mapping>
This is my calling place :
public class UserDAO {
private Session session = null;
public UserDAO() {
session = HibernateUtil.currentSession();
}
public List<User> getAllUsers() {
Transaction tn = session.beginTransaction();
List<User> users = session.createQuery("from crmusers cu order by cu.UserID").list();
System.out.println("==" + users.size());
tn.commit();
return users;
}
public static void main(String[] args){
UserDAO userDAO = new UserDAO();
userDAO.getAllUsers();
}
}
This is my project folder structre:
Please tell me what is an issue in my code?
Thanks in advance..
In User.hbm.xml you have to use type="java.lang.String" (with a big 'S'). That's it.
AS I understand the problem in your code was caused by your User.hbm.xml mapping file. To be more precised by type="string" attribute of composite-id tab.
As I understand you don't need to put type attribute obligatory so try to skip it at all; hibernate should detect it automatically. I'm not sure in last sentece because I have not used composite keys, but there are a lot of examples where peoples don't define type explicitly.
Hmmm, in your mapping file you have
<key-property name="businessUnit" column="BusinessUnit" type="string"/>
<key-property name="userID" column="UserID" type="string"/>
That should be ...type="java.lang.String"... instead, but most likely you really don't need it - Hibernate will make a (usually very good) educated guess.
Cheers,
Hibernate use the reflection to determine the mapping type at runtime.
It seems your mapping is correct, But if you still getting the same problem.
I will suggest you to remove the type attribute for the time being test, from all the String type properties such as email,businessUnit,userId
try this way for all the String type properties
<property name="email">
<column name="Email"/>
</property>
or you can try with java.lang.String also
<property name="email" type="java.lang.String">
<column name="Email"/>
</property>
Both "string" and "java.lang.String" are aliases for org.hibernate.type.StringType, so either should work in terms of naming types.
I am actually not so sure the problem is in the mapping for User. That mapping looks fine. Based on that exception I would more expect that somewhere you have
<composite-id ... class="string">
or
<component ... class="string">
or something like that.
<composite-id name="userPK" >
<key-property name="businessUnit" column="BusinessUnit" type="String"/>
<key-property name="userID" column="UserID" type="String"/>
</composite-id>
try with changing string to String

Categories