Data is inserted twice in database jpa/hibernate - java

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.

Related

Not able to inject HashMap Object using util namespace setter dependency injection in spring

I am trying to inject HashMap Object using util namespace but not able to get HashMap class for that Object (LinkedHashMap class name is getting printed.)
Not able to figure out why this is happening.
I am using below Spring jars in this test:
1. spring-beans-5.0.7.RELEASE.jar
2. spring-context-5.0.7.RELEASE.jar
3. spring-core-5.0.7.RELEASE.jar
4. spring-expression-5.0.7.RELEASE.jar
5. commons-logging-1.1.1.jar
Bean Class :
package com.vitp.pkg1;
import java.util.HashMap;
public class ActualCollections {
private HashMap<String,Integer> student;
public void setStudent(HashMap<String, Integer> student) {
this.student = student;
}
public void displayData()
{
System.out.println("Map data(Student<name,rollnumber>) : ---default is LinkedHashMap And actual is :: "+student.getClass().getName());
for(String key : student.keySet())
{
System.out.println(key+"::"+student.get(key));
}
}
}
Driver class to test the output :
package com.vitp.start;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.vitp.pkg1.ActualCollections;
import com.vitp.pkg1.DefaultCollections;
public class ActualCollectionObjectInjectionTest {
public static void main(String... s)
{
ApplicationContext beans = new ClassPathXmlApplicationContext("/com/vitp/resources/particular_collection.xml");
ActualCollections pc = (ActualCollections) beans.getBean("pc");
pc.displayData();
}
}
xml configuration file :
<!--In this case we need to make use of util namespace so will use xsd instate of dtd.-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<bean id="pc" class="com.vitp.pkg1.ActualCollections">
<!--Set Map attribute with setter injection-->
<property name="student">
<util:map map-class="java.util.HashMap">
<!-- demonstrating various ways on values for entry-->
<entry key="Sachin" value="1"/>
<!--way2-->
<entry key="Rahul">
<value>2</value>
</entry>
<!--way3-->
<entry key="Vinayak" value-ref="three"/>
<!--way4-->
<entry key="Salman">
<ref bean="four"/>
</entry>
</util:map>
</property>
</bean>
<bean id="three" class="java.lang.Integer">
<constructor-arg index="0">
<value>3</value>
</constructor-arg>
</bean>
<bean id="four" class="java.lang.Integer">
<constructor-arg index="0">
<value>4</value>
</constructor-arg>
</bean>
</beans>
And the result is :
Sep 09, 2018 7:17:03 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#27f8302d: startup date [Sun Sep 09 19:17:03 IST 2018]; root of context hierarchy
Sep 09, 2018 7:17:03 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [com/vitp/resources/particular_collection.xml]
Map data(Student<name,rollnumber>) : ---default is LinkedHashMap And actual is :: java.util.LinkedHashMap
Rahul::2
Vinayak::3
Sachin::1
Salman::4
I am expectting It should be HashMap class.
You are missing id property for Map. If you put id for map, it work.
Working code:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<bean id="pc" class="com.vitp.pkg1.ActualCollections">
<property name="student" ref="someId"/>
</bean>
<util:map id="someId" map-class="java.util.HashMap">
<!-- demonstrating various ways on values for entry-->
<entry key="Sachin" value="1"/>
<!--way2-->
<entry key="Rahul">
<value>2</value>
</entry>
<!--way3-->
<entry key="Vinayak" value-ref="three"/>
<!--way4-->
<entry key="Salman">
<ref bean="four"/>
</entry>
</util:map>
<bean id="three" class="java.lang.Integer">
<constructor-arg index="0">
<value>3</value>
</constructor-arg>
</bean>
<bean id="four" class="java.lang.Integer">
<constructor-arg index="0">
<value>4</value>
</constructor-arg>
</bean>
</beans>

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.

Hibernate is mapping again all .hbm files in every new tomcat session

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.

Spring3 JPA Persistence Exception on entityManagerFactory

I have an application using Spring 3.2.2 and Hibernate 3.6.0.Final. I made some configurations and the app works pretty well on the test environment, using Postgresql, etc.
Junit Stach trace:
enter code here
java.lang.AssertionError: Error creating bean with name 'entityManagerFactory' defined in class path resource [applicationContext.xml]:
Invocation of init method failed; nested exception is javax.persistence.PersistenceException:
[PersistenceUnit: P_PROJET] Unable to build EntityManagerFactory
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:context="http://www.springframework.org/schema/context"
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/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
<bean id="datasource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver" />
<property name="url" value="jdbc:postgresql://localhost:5432/projet" />
<property name="username" value="postgres" />
<property name="password" value="" />
</bean>
<bean id="persistenceUnitManager"
class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="defaultDataSource" ref="datasource"></property>
<property name="persistenceXmlLocation" value="classpath:META-INF/persistance.xml">
</property>
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitManager" ref="persistenceUnitManager"></property>
<property name="persistenceUnitName" value="P_PROJET"></property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<context:annotation-config></context:annotation-config>
</beans>
Persistance.Xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd ">
<persistence-unit name="P_PROJET" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
</properties>
</persistence-unit>
</persistence>
console stack trace:
INFO : org.springframework.context.support.ClassPathXmlApplicationContext - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext#4476128: startup date [Mon Apr 07 21:55:10 WET 2014]; root of context hierarchy
INFO : org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [applicationContext.xml]
INFO : org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
INFO : org.springframework.jdbc.datasource.DriverManagerDataSource - Loaded JDBC driver: org.postgresql.Driver
INFO : org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'P_PROJET'
INFO : org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
INFO : org.hibernate.cfg.Environment - Hibernate 3.6.0.Final
INFO : org.hibernate.cfg.Environment - hibernate.properties not found
INFO : org.hibernate.cfg.Environment - Bytecode provider name : javassist
INFO : org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
INFO : org.hibernate.ejb.Version - Hibernate EntityManager 3.6.0.Final
INFO : org.hibernate.ejb.Ejb3Configuration - Processing PersistenceUnitInfo [
name: P_PROJET
...]
INFO : org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.gestion.projet.entities.EquipeProjet
INFO : org.hibernate.cfg.annotations.EntityBinder - Bind entity com.gestion.projet.entities.EquipeProjet on table EquipeProjet
INFO : org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.gestion.projet.entities.MembreTache
INFO : org.hibernate.cfg.annotations.EntityBinder - Bind entity com.gestion.projet.entities.MembreTache on table MembreTache
INFO : org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.gestion.projet.entities.User
INFO : org.hibernate.cfg.annotations.EntityBinder - Bind entity com.gestion.projet.entities.User on table User
INFO : org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.gestion.projet.entities.Projet
INFO : org.hibernate.cfg.annotations.EntityBinder - Bind entity com.gestion.projet.entities.Projet on table Projet
INFO : org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.gestion.projet.entities.Phase
INFO : org.hibernate.cfg.annotations.EntityBinder - Bind entity com.gestion.projet.entities.Phase on table Phase
INFO : org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.gestion.projet.entities.Role
INFO : org.hibernate.cfg.annotations.EntityBinder - Bind entity com.gestion.projet.entities.Role on table Role
INFO : org.hibernate.cfg.AnnotationBinder - Binding entity from annotated class: com.gestion.projet.entities.Tache
INFO : org.hibernate.cfg.annotations.EntityBinder - Bind entity com.gestion.projet.entities.Tache on table Tache
INFO : org.hibernate.cfg.annotations.CollectionBinder - Mapping collection: com.gestion.projet.entities.EquipeProjet.user -> User
INFO : org.hibernate.cfg.annotations.CollectionBinder - Mapping collection: com.gestion.projet.entities.User.membretache -> MembreTache
INFO : org.hibernate.cfg.annotations.CollectionBinder - Mapping collection: com.gestion.projet.entities.Projet.phases -> Phase
INFO : org.hibernate.cfg.annotations.CollectionBinder - Mapping collection: com.gestion.projet.entities.Phase.tache -> Tache
INFO : org.hibernate.cfg.annotations.CollectionBinder - Mapping collection: com.gestion.projet.entities.Tache.membreTaches -> MembreTache
INFO : org.hibernate.cfg.Configuration - Hibernate Validator not found: ignoring
INFO : org.hibernate.cfg.search.HibernateSearchEventListenerRegister - Unable to find org.hibernate.search.event.FullTextIndexEventListener on the classpath. Hibernate Search is not enabled.
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory#8c3c315: defining beans [datasource,persistenceUnitManager,entityManagerFactory,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
Looks like you're missing the hibernate-search jar.
See http://hibernate.org/search/

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

I need help fixing this error I get when trying to deploy my web application into tomcat. Why isn't the customerService bean being defined? Am I missing something in my web.xml or do I have to map the customerService somehow? I am using annotations for mapping. any help would be much appreciated. Here is the error log entry from the localhost log:
Error:
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:306)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
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:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:384)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4600)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5097)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5092)
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)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:529)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1095)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:277)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:442)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:416)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:549)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:150)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:303)
... 21 more
Apr 30, 2012 11:17:09 AM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
Apr 30, 2012 11:23:19 AM org.apache.catalina.core.ApplicationContext log
INFO: SessionListener: contextDestroyed()
Apr 30, 2012 11:23:19 AM org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: contextDestroyed()
Apr 30, 2012 11:23:20 AM org.apache.catalina.core.ApplicationContext log
INFO: Destroying Spring FrameworkServlet 'spring'
Apr 30, 2012 11:23:20 AM org.apache.catalina.core.ApplicationContext log
INFO: Closing Spring root WebApplicationContext
Apr 30, 2012 11:23:27 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Apr 30, 2012 11:23:33 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'spring'
Apr 30, 2012 11:23:35 AM org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: contextInitialized()
Apr 30, 2012 11:23:35 AM org.apache.catalina.core.ApplicationContext log
INFO: SessionListener: contextInitialized()
Apr 30, 2012 11:23:57 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Apr 30, 2012 11:23:58 AM org.apache.catalina.core.StandardContext listenerStart
SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerController': Injection of resource dependencies failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:306)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
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:585)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:384)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:283)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4600)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5097)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5092)
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)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:529)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1095)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:277)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:442)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:416)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:549)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:150)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:303)
... 21 more
web.xml (mistest/WebContent/WEB-INF) *Updated*
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/mistest/*</url-pattern>
</servlet-mapping>
<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>
</web-app>
customerService
package testapp.mis.service;
import java.util.List;
import testapp.mis.domain.Customer;
public interface CustomerService {
public List<Customer> retrieveAllCustomerNames();
public List<Customer> retrieveAllCustomerCountries();
public void createCustomer(Customer customer);
public List<Customer> retrieveAllCustomers();
}
thanks for the help, let me know if I need to put up any other files.
Edit: Here is the applicationContext.xml and the customerService Implementation files:
applicationContext.xml (mistest/WebContent/WEB-INF) *Updated*
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<context:annotation-config/>
<context:component-scan base-package="testapp.mis"/>
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="0"/>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages"/>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
</beans>
customerServiceImpl:
package testapp.mis.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import testapp.mis.dao.CustomerDao;
import testapp.mis.domain.Customer;
#Service
public class CustomerServiceImpl implements CustomerService {
#Autowired(required=true)
private CustomerDao customerDao;
#Transactional
public List<Customer> retrieveAllCustomerNames() {
return this.customerDao.getAllCustomerNames();
}
#Transactional
public List<Customer> retrieveAllCustomerCountries() {
return this.customerDao.getAllCustomerCountries();
}
#Transactional
public void createCustomer(Customer customer){
this.customerDao.saveCustomer(customer);
}
#Transactional
public List<Customer> retrieveAllCustomers(){
return this.customerDao.getAllCustomers();
}
}
Edit2:
Here is the CustomerController. I added the #Autowired as suggested.
package testapp.mis.controller;
//import javax.annotation.Resource;
import java.util.List;
import testapp.mis.service.CustomerService;
import testapp.mis.domain.Customer;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.beans.factory.annotation.Autowired;
#Controller
#RequestMapping("/customer")
public class CustomerController {
/*#Resource(name="customerService")
private CustomerService customerService;
*/
#Autowired
private CustomerService customerService;
#RequestMapping(value="/list", method=RequestMethod.GET)
public String getCustomerList(Model model) {
List<Customer> customers = customerService.retrieveAllCustomers();
System.out.println("test");
model.addAttribute("customerList", customers);
return "customer";
}
#RequestMapping(value="/add", method=RequestMethod.GET)
public String getCustomer(Model model) {
model.addAttribute("customerAttribute", new Customer());
return "new-customer";
}
#RequestMapping(value="/add", method=RequestMethod.POST)
public String postCustomer(#ModelAttribute("customerAttribute") Customer customer) {
customerService.createCustomer(customer);
return "redirect:/mis/customer/list";
}
}
spring-servlet.xml (mistest/WebContent/WEB-INF)
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<!-- Declare a view resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
</beans>
hibernate-context.xml (mistest/WebContent/WEB-INF)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
">
<context:property-placeholder location="/WEB-INF/spring.properties" />
<!-- Enables annotations for transaction management -->
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- Declare the Hibernate SessionFactory for retrieving Hibernate sessions -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="${hibernate.config}"
p:packagesToScan="testapp.mis"/>
<!-- Declare a datasource that has pooling capabilities-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close"
p:driverClass="${app.jdbc.driverClassName}"
p:jdbcUrl="${app.jdbc.url}"
p:user="${app.jdbc.username}"
p:password="${app.jdbc.password}"
p:acquireIncrement="5"
p:idleConnectionTestPeriod="60"
p:maxPoolSize="100"
p:maxStatements="50"
p:minPoolSize="10" />
<!-- Declare a transaction manager-->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
</beans>
hibernate.cfg.xml (mistest/WebContent/WEB-INF)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- We're using MySQL database so the dialect needs to MySQL as well-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- Enable this to see the SQL statements in the logs-->
<property name="show_sql">false</property>
<!-- Remove after testing -->
<!-- This will drop our existing database and re-create a new one.
Existing data will be deleted! -->
<property name="hbm2ddl.auto">create</property>
</session-factory>
</hibernate-configuration>
/D
By reading your exception , It's sure that you forgot to autowire customerService
You should autowire your customerservice .
make following changes in your controller class
#Controller
public class CustomerController{
#Autowired
private Customerservice customerservice;
......other code......
}
Again your service implementation class
write
#Service
public class CustomerServiceImpl implements CustomerService {
#Autowired
private CustomerDAO customerDAO;
......other code......
.....add transactional methods
}
If you are using hibernate make necessary changes in your applicationcontext xml file(configuration of session factory is needed).
you should autowire sessionFactory set method in your DAO mplementation
please find samle application context :
<?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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:lang="http://www.springframework.org/schema/lang"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:annotation-config />
<context:component-scan base-package="com.sparkle" />
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven />
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="0" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:messages" />
<property name="defaultEncoding" value="UTF-8" />
</bean>
<!-- <bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" /> -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>/WEB-INF/jdbc.properties</value>
</list>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory"/>
</beans>
note that i am using jdbc.properties file for jdbc url and driver specification
You will have to annotate your service with #Service since you have said I am using annotations for mapping
Please make sure that your applicationContext.xml file is loaded by specifying it in your web.xml file:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
Just another possibility:
Spring initializes bean by type not by name if you don't define bean with a name, which is ok if you use it by its type:
Producer:
#Service
public void FooServiceImpl implements FooService{}
Consumer:
#Autowired
private FooService fooService;
or
#Autowired
private void setFooService(FooService fooService) {}
but not ok if you use it by name:
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ctx.getBean("fooService");
It would complain: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'fooService' is defined
In this case, assigning name to #Service("fooService") would make it work.

Categories