Error creating bean 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#1' - spring

I'm trying to create a web-app, using Maven and Intellij Idea. Tests work fine as installing in .war-file. But when I try to refer to my rest with jetty, I have lots of error cases:
Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#1' defined in ServletContext resource [/WEB-INF/rest-spring.xml]: Initialization of bean failed;
nested exception is java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonProcessingException
Here are rest module files:
Web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5"
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_2_5.xsd">
<servlet>
<servlet-name>restDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--the location of the spring context configuration file-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/rest-spring.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>restDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
rest-spring.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:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:context="http://www.springframework.org/schema/context"
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/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.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">
<mvc:annotation-driven/>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:model.properties</value>
<value>classpath:database.properties</value>
<value>classpath:automobile.properties</value>
</list>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<jdbc:initialize-database data-source="dataSource">
<jdbc:script location="classpath*:create-tables-model.sql"/>
<jdbc:script location="classpath*:create-tables-automobile.sql"/>
<jdbc:script location="classpath*:data-script.sql"/>
</jdbc:initialize-database>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonConverter"/>
</list>
</property>
</bean>
<bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes" value="application/json" />
<property name="prettyPrint" value="true" />
</bean>
<bean id="modelDao" class="com.dao.ModelDaoImpl">
<constructor-arg ref="dataSource" />
</bean>
<bean id="automobileDao" class="com.dao.AutomobileDaoImpl">
<constructor-arg ref="dataSource" />
</bean>
<bean id="modelService" class="com.service.ModelServiceImpl">
<property name = "modelDao" ref = "modelDao"/>
</bean>
<bean id="automobileService" class="com.service.AutomobileServiceImpl">
<property name = "automobileDao" ref = "automobileDao"/>
</bean>
<context:component-scan base-package="com.rest"/>
</beans>
ModelRestController
package com.rest;
import com.dto.ModelDto;
import com.general.Model;
import com.service.ModelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.List;
/**
* Created by kohtpojiep on 23.01.16.
*/
#RestController
public class ModelRestController
{
private static final Logger LOGGER = LogManager.getLogger();
#Autowired
private ModelService modelService;
#RequestMapping(value="/models", method = RequestMethod.GET)
public #ResponseBody List<Model> getAllModels()
{
LOGGER.debug("Getting all models");
return modelService.getAllModels();
}
#RequestMapping(value="/model", method = RequestMethod.POST)
#ResponseStatus(value = HttpStatus.CREATED)
public #ResponseBody Integer addModel(#RequestBody Model model)
{
LOGGER.debug("Adding model modelName = {}", model.getModelName());
return modelService.addModel(model);
}
#RequestMapping (value="/model/{modelId}/{modelName}", method=RequestMethod.PUT)
#ResponseStatus(value = HttpStatus.ACCEPTED)
public #ResponseBody void updateModel(#PathVariable(value="modelId") Integer modelId,
#PathVariable(value="modelName") String modelName)
{
LOGGER.debug("Updating model modelId = {}", modelId);
modelService.updateModel(new Model(modelId,modelName));
}
#RequestMapping (value="/model/{modelName}", method = RequestMethod.DELETE)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public #ResponseBody void deleteModelByName(#PathVariable(value = "modelName") String modelName)
{
LOGGER.debug("Deleting model modelName= {}",modelName);
modelService.deleteModelByName(modelName);
}
#RequestMapping (value="/modelsdto", method = RequestMethod.GET)
#ResponseStatus(value = HttpStatus.OK)
public #ResponseBody
ModelDto getModelsDto()
{
LOGGER.debug("Getting models Dto");
return modelService.getModelDto();
}
}
AutomobileRestController
package com.rest;
import com.dto.AutomobileDto;
import com.general.Automobile;
import com.service.AutomobileService;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.List;
/**
* Created by kohtpojiep on 02.02.16.
*/
#RestController
public class AutomobileRestController
{
private static final Logger LOGGER = LogManager.getLogger();
#Autowired
AutomobileService automobileService;
private static LocalDate convertToLocalDate(String date)
{
DateTimeFormatter formattedDate = DateTimeFormat.forPattern("dd/MM/yyyy");
return formattedDate.parseLocalDate(date);
}
#RequestMapping(value = "/automobiles", method = RequestMethod.GET)
#ResponseStatus(value = HttpStatus.ACCEPTED)
public #ResponseBody List<Automobile> getAllAutomobiles()
{
LOGGER.debug("Getting all automobiles");
return automobileService.getAllAutomobiles();
}
#RequestMapping(value = "/automobile", method = RequestMethod.POST)
#ResponseStatus(value = HttpStatus.CREATED)
public #ResponseBody Integer addAutomobile (#RequestBody Automobile automobile)
{
LOGGER.debug("Adding automobile modelName = {}",automobile.getModelName());
return automobileService.addAutomobile(automobile);
}
#RequestMapping(value = "/automobile/update", method = RequestMethod.PUT)
#ResponseStatus(value = HttpStatus.ACCEPTED)
public #ResponseBody void updateAutomobile (#RequestBody Automobile automobile)
{
LOGGER.debug("Updating automobile automobileId = {}", automobile.getAutomobileId());
automobileService.updateAutomobile(automobile);
}
#RequestMapping(value = "/automobile/{automobileId}", method = RequestMethod.DELETE)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public #ResponseBody void depeteAutomobile (#PathVariable (value="automobileId")
Integer automobileId)
{
LOGGER.debug("Deleting automobile automobileId = {}",automobileId);
automobileService.deleteAutomobileById(automobileId);
}
#RequestMapping(value = "/automobiles/date-sort", method = RequestMethod.GET)
#ResponseStatus(value = HttpStatus.ACCEPTED)
public #ResponseBody List<Automobile> getAutomobilesSortedByDate (#RequestParam(value="firstDate")
String firstDate, #RequestParam (value="lastDate") String lastDate)
{
LOGGER.debug("Getting automobiles sorted by date:\n");
return automobileService.getAutomobilesSortedByDate(
convertToLocalDate(firstDate),convertToLocalDate(lastDate));
}
#RequestMapping(value = "/automobilesdto", method = RequestMethod.GET)
#ResponseStatus(value = HttpStatus.OK)
public #ResponseBody
AutomobileDto getAutomobileDto()
{
LOGGER.debug("Getting automobile DTO");
return automobileService.getAutomobileDto();
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>usermanagement</artifactId>
<groupId>com.epam.brest.course2015</groupId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>app-rest</artifactId>
<name>${project.artifactId}</name>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>com.epam.brest.course2015</groupId>
<artifactId>app-service</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>org.easymock</groupId>
<artifactId>easymock</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>8.1.16.v20140903</version>
<configuration>
<stopPort>9091</stopPort>
<stopKey>STOP</stopKey>
<webAppConfig>
<contextPath>/rest</contextPath>
<allowDuplicateFragmentNames>true</allowDuplicateFragmentNames>
</webAppConfig>
<scanIntervalSeconds>10</scanIntervalSeconds>
<connectors>
<connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
<port>8081</port>
</connector>
</connectors>
</configuration>
</plugin>
</plugins>
</build>
</project>
I saw solutions for similar situations: people offer to change versions of used frameworks and up the search level of component scan, but it doesn't work for me.

Add dependency to your POM:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
As you use dependency management in parent POM, there is no need to specify version.

Solved! The problem was I use not only jackson-core dependency, but also jackson databind, datatype and annotations and these dependencies had different versions: 2.7.1 for "core" and 2.4.3 for other ones. Now I use the same version for all of them and thus adding dependency had an affect. Thx for your help!)

I had the same problem. I used spring version 5.0.5.RELEASE and Jackson Core version 2.4.3.
I upgraded Jackson core up to 2.9.5 and it works now : exception "Error creating bean with name 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter' " dissapeared and my rest service works.
Before in my pom.xml :
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.4.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.4.3</version>
</dependency>
After :
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
I hope it will help.

Yes. Using version 2.9.5 works:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</exclusion>
</exclusions>
</dependency>
I'm using spring-webmvc: 5.0.12.RELEASE, if that helps.

Related

#Service Spring as Managed property of ManagedBean class in jsf is null

I've a webapp using JSF + Spring + Maven + JBoss (java 8).
I've a class ManagedBean with a property ManagedProperty which is a service spring.
In remote debugging I checked that the service is not injected and is null.
No errors in console (or server.log).
java class
#ManagedBean(name = "userBean")
#SessionScoped
public class UserBean implements Serializable {
...
#ManagedProperty(value = "#{loggedUserSession}")
private ILoggedUserSession loggedUserSession;
public String getUserLogin() {
return loggedUserSession.getUser();
}
public ILoggedUserSession getLoggedUserSession() {
return loggedUserSession;
}
public void setLoggedUserSession(ILoggedUserSession loggedUserSession) {
this.loggedUserSession = loggedUserSession;
}
...
}
service java class
#Service("loggedUserSession")
#Scope(value = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class LoggedUserSessionImpl implements ILoggedUserSession, Serializable {...}
pom.xml
...
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.1.4.RELEASE</version>
</dependency>
<dependency>
<groupId>com.sun.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>2.2.13</version>
</dependency>
<dependency>
<groupId>org.primefaces</groupId>
<artifactId>primefaces</artifactId>
<version>6.2</version>
</dependency>
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0.SP1</version>
</dependency>
...
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
In the applicationContext.xml i mapped <context:component-scan ... /> and
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:conf.properties</value>
</property>
</bean>
I noticed the error at runtime.
I checked in web.xml, faces-config, applicationContext.xml and pom.xml but I didn't find anything strange.

Invocation of init method failed; nested exception is javax.persistence.PersistenceException

Guys i've came across a problem which i googled a lot and tried to find solutions in stackflow,however it failed and there seems no body have met with the same problem .What's more , i've got exhausted.Below is my code and configuration files.
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.robot</groupId>
<artifactId>springdata</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<dependencies>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.8.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-
data-jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.8.0.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/hibernate/hibernate-entitymanager --
>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.6.Final</version>
</dependency>
</dependencies>
</project>
in my dependency xml,i add spring data and hibernate.
<?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"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="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.3.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.0.xsd">
<!--1 配置数据源-->
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
<property name="driverClassName" value="com.mysql.jdbc.Driver">
</property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
<property name="url" value="jdbc:mysql:///spring_data"></property>
</bean>
<!--2 配置EntityManagerFactory-->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
</property>
<property name="packagesToScan" value="com.robot"/>
<property name="jpaProperties">
<props>
<prop
key="hibernate.ejb.naming_strategy">
org.hibernate.cfg.ImprovedNamingStrategy</prop>
<prop
key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<!--<!–3 配置事务管理器–>-->
<!--<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">-->
<!--<property name="entityManagerFactory" ref="entityManagerFactory"/>--
>
<!--</bean>-->
<!--<!–4 配置支持注解的事务–>-->
<!--<tx:annotation-driven transaction-manager="transactionManager"/>-->
<!--<!–5 配置spring data–>-->
<!--<jpa:repositories base-package="com.robot" entity-manager-factory-
ref="entityManagerFactory"/>-->
<!--<context:component-scan base-package="com.robot"/>-->
</beans>
below is my entity class, it is very simple,so i don't think any thing will go wrong.
package com.robot.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
#Entity
public class Employee {
private int id;
private String name;
private int age;
public int getId() {
return id;
}
#GeneratedValue
#Id
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
below is my test class
package com.robot.dao;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class StudentSpringDataTest {
private ApplicationContext ctx=null;
#Before
public void setUp(){
System.out.println("Set Up");
ctx= new ClassPathXmlApplicationContext("beans_new.xml");
}
#After
public void tearDown(){
System.out.println("Tear Down");
ctx =null;
}
#Test
public void initializationTest(){
}
}
when i run the initializationTest method it show error like the picture described.
log info
For your next questions do not include your stack traces as image.
The error is clear: "No identifier specified for entity: ....", and that is because you have your #Id annotation on a set method, and you can not use annotation on settters. You need to use it either on the field or on the getter method.
Hibernate mapping annotations - Access type
Try:
#Entity
public class Employee {
#GeneratedValue
#Id
private int id;
...
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
...
}

2023 [localhost-startStop-1] INFO org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping not load when running tomcat

How to config for loading this package
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping.
When i run Tomcat everything i got only as below:
0 [localhost-startStop-1] INFO org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization started
65 [localhost-startStop-1] INFO org.springframework.web.context.support.XmlWebApplicationContext - Refreshing Root WebApplicationContext: startup date [Fri Mar 11 21:55:33 EET 2016]; root of context hierarchy
366 [localhost-startStop-1] INFO org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/applicationContext.xml]
470 [localhost-startStop-1] INFO org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from ServletContext resource [/WEB-INF/spring-data.xml]
836 [localhost-startStop-1] INFO org.springframework.context.support.PropertySourcesPlaceholderConfigurer - Loading properties file from URL [file:/Volumes/Data/JavaEE/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/d14-spring_mvc/WEB-INF/classes/db_connection.properties]
1045 [localhost-startStop-1] INFO org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 1042 ms
So i got problem about DispatcherServlet can't find mapping uri with servlet.
1735055 [http-nio-8001-exec-5] WARN org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/vietjob/tyopaikka.lista] in DispatcherServlet with name 'vietjob'
pom.xlm
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>vjb.de</groupId>
<artifactId>vietjob</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>vietjob Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>4.0.0.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.jumpmind.symmetric.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.0.3.Final</version>
</dependency>
</dependencies>
<build>
<finalName>vietjob</finalName>
</build>
</project>
servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- Configures the #Controller programming model -->
<mvc:annotation-driven />
<context:component-scan base-package="vjb.de.vietjob" />
<!-- Resolves view names to protected .jsp resources within the /WEB-INF/views
directory -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- Forwards requests to the "/" resource to the "welcome" view -->
<mvc:view-controller path="/" view-name="index" />
<!-- location of static content (images, js and css files) -->
<mvc:resources mapping="/resources/**" location="/resources/" />
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="classpath:lang" />
<property name="defaultEncoding" value="UTF-8"/>
</bean>
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
<property name="defaultLocale" value="en" />
</bean>
<mvc:interceptors>
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
<property name="paramName" value="lang" />
</bean>
</mvc:interceptors>
</beans>
Controller
package vjb.de.vietjob.controller;
import java.util.List;
import javax.inject.Inject;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import vjb.de.vietjob.bean.Duuni;
import vjb.de.vietjob.bean.EhdokasImpl;
import vjb.de.vietjob.dao.DuuniDao;
#Controller
#RequestMapping(value = "/")
public class DuuniController {
#Inject
private DuuniDao duunidao;
public DuuniDao getDuuniDao() {
return this.duunidao;
}
public void setDuuniDao(DuuniDao duunidao) {
this.duunidao = duunidao;
}
// Metodi näyttä kaikki työpaikat, jotka ovat oleva tietokannasta
#RequestMapping(value = "/tyopaikka.lista", method = RequestMethod.GET)
public String showDuuni(Model model) {
List<Duuni> duunit = duunidao.showDuuni();
model.addAttribute("duunit", duunit);
return "duuni/tyopaikka";
}
// Metodi kotisivulle
#RequestMapping(value = "/", method = RequestMethod.GET)
public String returnIndex() {
return "index";
}
// Metodi näyttää lisätietoja työpaikasta
#RequestMapping(value = "/tyopaikka.lista/{id}", method = RequestMethod.GET)
public String showYksiDuuni(
#RequestParam(value = "id", required = false) Integer id,
Model model) {
Duuni duuni = duunidao.showYksiDuuni(id);
model.addAttribute("duuni", duuni);
return "duuni/yksipaikka";
}
// Metodi luo uusi ehdokkaan lomake
#RequestMapping(value = "lomake.luo", method = RequestMethod.POST)
public String getUusiEhdokas(
#ModelAttribute(value = "ehdokas") #Valid EhdokasImpl ehdokas,
BindingResult result) {
return "lomake/ehdokas_lomake";
}
}
Controller modify
package vjb.de.vietjob.controller;
import java.util.List;
import javax.inject.Inject;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import vjb.de.vietjob.bean.Duuni;
import vjb.de.vietjob.bean.EhdokasImpl;
import vjb.de.vietjob.dao.DuuniDao;
#Controller
/*#RequestMapping(value = "/")*/
public class DuuniController {
#Inject
private DuuniDao duunidao;
public DuuniDao getDuuniDao() {
return this.duunidao;
}
public void setDuuniDao(DuuniDao duunidao) {
this.duunidao = duunidao;
}
// Metodi näyttä kaikki työpaikat, jotka ovat oleva tietokannasta
#RequestMapping(value = "tyopaikka.lista", method = RequestMethod.GET)
public String showDuuni(Model model) {
List<Duuni> duunit = duunidao.showDuuni();
model.addAttribute("duunit", duunit);
return "duuni/tyopaikka";
}
#RequestMapping(value = "/tyopaikka.lista", method = RequestMethod.GET)
public String showDuuni1(Model model) {
List<Duuni> duunit = duunidao.showDuuni();
model.addAttribute("duunit", duunit);
return "duuni/tyopaikka";
}
#RequestMapping(value = "vietjob/tyopaikka.lista", method = RequestMethod.GET)
public String showDuuni2(Model model) {
List<Duuni> duunit = duunidao.showDuuni();
model.addAttribute("duunit", duunit);
return "duuni/tyopaikka";
}
#RequestMapping(value = "/vietjob/tyopaikka.lista", method = RequestMethod.GET)
public String showDuuni3(Model model) {
List<Duuni> duunit = duunidao.showDuuni();
model.addAttribute("duunit", duunit);
return "duuni/tyopaikka";
}
// Metodi kotisivulle
#RequestMapping(value = "/", method = RequestMethod.GET)
public String returnIndex() {
return "index";
}
}
Your controller class has a top level #RequestMapping("/"), try changing that to #RequestMapping("/vietjob").

The object doesn't get persisted in Hibernate 4

I configured Hibernate and Spring.
The config and Java class:
package com.dao.impl;
import com.dao.IPersonRepository;
import com.dao.impl.generic.GenericRepository;
import com.model.Person;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by ramezanimatin on 8/18/2015.
*/
#Repository
public class PersonRepository extends GenericRepository<Person, Long> implements IPersonRepository {
}
package com.dao;
import com.dao.iGeneric.IGenericRepository;
import com.model.Person;
/**
* Created by ramezanimatin on 8/18/2015.
*/
public interface IPersonRepository extends IGenericRepository<Person, Long> {
}
package com.dao.iGeneric;
import java.io.Serializable;
/**
* Created by ramezanimatin on 8/23/2015.
*/
public abstract interface IGenericRepository<T, pk extends Serializable> {
public void save(T t);
public T loadByEntityId(pk id);
}
package com.dao.impl.generic;
import com.dao.iGeneric.IGenericRepository;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
/**
* Created by ramezanimatin on 8/23/2015.
*/
#Repository
public class GenericRepository<T, pk extends Serializable> implements IGenericRepository<T, pk> {
#Autowired(required = true)
private SessionFactory sessionFactory;
private Session getSession() {
try {
return sessionFactory.getCurrentSession();
} catch (Exception e) {
return sessionFactory.openSession();
}
}
#Override
public void save(Object o) {
getSession().save(o);
}
#Override
public T loadByEntityId(pk id) {
Session session = getSession();
Query query = session.createQuery("from Person e where e.id=:id");
query.setParameter("id", id);
return ((T) query.uniqueResult());
}
}
xml config:
<?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" xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.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/jee http://www.springframework.org/schema/jee/spring-jee.xsd">
<context:property-placeholder location="classpath:oracle-hibernate.properties"/>
<context:component-scan base-package="com"/>
<!-- <jee:jndi-lookup id="dataSource" jndi-name="test" />-->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.model"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">create</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql"> ${hibernate.show_sql}</prop>
<prop key="hibernate.default_schema"> ${hibernate.default_schema}</prop>
<prop key="hibernate.connection.defaultNChar">true</prop> <!--Oracle need -->
<prop key="hibernate.connection.characterEncoding">UTF8</prop> <!--Oracle need -->
<prop key="hibernate.connection.charSet">UTF8</prop> <!--Oracle need -->
<prop key="hibernate.connection.useEncoding">true</prop> <!--Oracle need -->
<prop key="hibernate.transaction.factory_class" >${hibernate.transaction.factory_class}</prop>
<!-- <prop key="hibernate.transaction.manager_lookup_class" >${hibernate.transaction.manager_lookup_class}</prop>
<prop key="hibernate.current_session_context_class" >${hibernate.current_session_context_class}</prop>-->
</props>
</property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="true"/>
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
</beans>
personService:
package com.service.impl;
import com.dao.IPersonRepository;
import com.model.Person;
import com.service.IPersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Created by ramezanimatin on 8/15/2015.
*/
#Service
public class PersonService implements IPersonService {
#Autowired(required = true)
private IPersonRepository iPersonRepository;
#Override
#Transactional
public void insertPerson(Person person) {
iPersonRepository.save(person);
}
#Override
#Transactional
public void loadByEntityId(Long id) {
Person person = iPersonRepository.loadByEntityId(id);
System.out.println(person.getName());
person.setName("matin");
}
}
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.test</groupId>
<artifactId>test</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
<version>3.2.0.Final</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.1.2.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.0.7.RELEASE</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.12.0.GA</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>javax.transaction</groupId>
<artifactId>jta</artifactId>
<version>1.1</version>
</dependency>
<!-- jpa lib-->
</dependencies>
<build>
<finalName>test</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
My problem:
In Hibernate the Object Model has 3 states:
1- Transient
2- Persistent
3- Detached
I want to clarify the following situation:
When Object Model is fetched from the DataBase, it is Persistent. In loadByEntityId of PersonService when the Person Entity is loaded, It isn't persistent. Why?
I changed name to 'Matin' but didn't commited to DataBase.
Updated:
Thanks to M. Deinum for explain subtle differences.
Please remove this method:
private Session getSession() {
try {
return sessionFactory.getCurrentSession();
} catch (Exception e) {
return sessionFactory.openSession();
}
}
and just invoke getCurrentSession() for example:
Session session = sessionFactory.getCurrentSession();
In this method:
#Override
#Transactional
public void loadByEntityId(Long id) {
Person person = iPersonRepository.loadByEntityId(id);
System.out.println(person.getName());
person.setName("matin");
}
you have found Person entity and it's pretty much done. Under the hood you are using session in Hibernate so this particular code:
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from Person e where e.id=:id");
query.setParameter("id", id);
return ((T) query.uniqueResult());
only retrieve data.
What you need to do is define update method in your repository IGenericRepository interface:
public abstract interface IGenericRepository<T, pk extends Serializable> {
public void save(T t);
public T loadByEntityId(pk id);
public void updateEntity(T t);
}
implement it in GenericRepository:
#Override
public void updateEntity(T entity) {
getSession().update(entity);
}
define in IPersonService method updatePerson and implement it in PersonService and use updateEntity from Repostitory:
#Override
#Transactional
public void updatePerson(Person person) {
iPersonRepository.updateEntity(person);
}
And now when you use loadByEntityId after you have updated Person with updatePerson you should retrieve updated entity from db.

Understanding how nested Spring #Transactional works

I'm porting an EJB application to Spring and I'm facing some issues.
The application is running in standalone (that's why we choose spring) with eclipselink.
In this application I need to create an Order, for which I first need to create a Customer, the OrderLines and then add a Payment for this Order.
The problem is that I want to do all the insertion in a single Transaction so that if the payment fails to be persisted nothing must be persisted. I tried to achieve this but it looks like I'm spanning multiple independent transaction because in case of failure data are persisted to th DB (ex: payment fails, customer is created anyway).
Here is the entry point :
public static void main(String[] args) {
AbstractApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "applicationContext.xml" });
BeanFactory beanFactory = (BeanFactory) context;
MyService service = beanFactory.getBean(MyService.class);
service.getNewOrders(true);
}
Here is the bean I'm resolving (using beanFactory.getBean) :
#Component
#Scope("prototype")
public class MyService {
#Autowired
private CustomerService customerService;
#Autowired
private OrderService orderService;
#Autowired
private PaymentService paymentService;
#Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public void getNewOrders(boolean formattedOutput) {
try {
List<RawData> rawData = // Acquire data from a remote web service (http rest based)
for (RawData data : rawData) {
try {
this.handleOrder(data);
} catch (Exception ex) {
ex.printStackTrace();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Transactional(propagation = Propagation.REQUIRES_NEW)
private Order handleOrder(RawData rawData) throws Exception {
Customer customer = new Customer();
// Fill customer with rawData
this.customerService.create(customer);
Order order = new Order();
order.setCustomer(customer);
// Fill order with rawData
this.orderService.create(order);
Payment payment = new Payment();
payment.setOrder(order);
// Fill payment with rawData
this.paymentService.create(payment);
return order;
}
}
Each service looks like the following :
#Service
#Transactional
public class CustomerService {
#Autowired
private CustomerDao customerDao;
public void create(Customer customer) {
// some works on customer fields (checking values etc)
this.customerDao.create(customer);
}
}
Which are all backed by a Dao :
#Repository
public class CustomerDao {
#PersistenceContext
protected EntityManager em;
public void create(Customer customer) {
this.em.persist(customer);
}
}
Here are a few dependencies from maven pom.xml :
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>com.jolbox</groupId>
<artifactId>bonecp</artifactId>
<version>0.8.0-rc1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.25</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.0.3</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
<version>2.3.2</version>
</dependency>
Here is the persistence.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="default" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<shared-cache-mode>NONE</shared-cache-mode>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/db" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="" />
</properties>
</persistence-unit>
</persistence>
The spring configuration is the following :
<?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: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-3.2.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 class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="myDataSource" class="com.jolbox.bonecp.BoneCPDataSource" destroy-method="close">
<property name="driverClass" value="com.mysql.jdbc.Driver" />
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/db" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="jpaPropertyMap">
<map>
<entry key="eclipselink.weaving" value="false" />
</map>
</property>
</bean>
<bean id="myTxManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEmf" />
</bean>
<tx:annotation-driven transaction-manager="myTxManager" />
<context:component-scan base-package="com.application" />
</beans>
EDIT
Added the creation of the ApplicationContext from the main, and an omitted method from MyService.java
How can you call the service method since it's private? It should be public. Private methods can't be intercepted by the Spring transactional interceptor, and can't be overridden by the CGLib dynamic proxy.
EDIT: OK, it's the usual problem. You're calling, from the main method, the method getNewOrders(), which is public and transactional. The Spring interceptor intercepts this method call. Since there is no transaction and the method is marked as SUPPORTS, Spring doesn't start any transaction.
Then this method calls the private handleOrder() method. Note that not only the method is private, which makes it impossible for Spring to intercept the method call, but the call is from a method in a component to a method in the same component. So even is the method was public, Spring could not intercept this method call. The transactional handling is proxy-based:
method --> transactional proxy --> Spring bean 1 --> transactional proxy --> Spring bean2
In this case, since you're not calling a method of another component, there is no proxy interception, and no transaction is started.
method --> transactional proxy --> Spring bean 1 --> transactional proxy --> Spring bean2
^ |
|___|
So, what you have to do is
create another Spring bean 'OrderHandler, for example)
move the handleOrder() method to this Spring bean, make it public
inject OrderHandler in MyService
And it will work fine.
This is explained in details in the Spring documentation.

Resources