1
votes

I am using Spring 3.1 and Eclipselink 2 with Tomcat, but for some reason data is not persisting.. The table is being generated though.

dispatcher-servlet.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
   http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="com.myapp.user.controllers" />
<mvc:annotation-driven />

<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

<bean id="viewResolver"
      class="org.springframework.web.servlet.view.InternalResourceViewResolver"
      p:prefix="/WEB-INF/jsp/"
      p:suffix=".jsp" />

</beans>

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"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd 
   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<aop:aspectj-autoproxy />

<context:load-time-weaver aspectj-weaving="on"/>


<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

<bean id="loadTimeWeaver" class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
    
<bean id="jpaVendorAdapter"
      class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
    <property name="database" value="MYSQL"/>
    <property name="showSql" value="true"/>
    <property name="generateDdl" value="false"/>
    <property name="databasePlatform" value="org.eclipse.persistence.platform.database.MySQLPlatform"/>
</bean>

<bean id="entityManagerFactory"
      class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
      p:persistenceUnitName="myAppPU"
      p:persistenceXmlLocation="classpath*:META-INF/persistence.xml"
      p:jpaVendorAdapter-ref="jpaVendorAdapter"
      p:loadTimeWeaver-ref="loadTimeWeaver"
      p:dataSource-ref="dataSource"
/>

<bean id="txManager"
      class="org.springframework.orm.jpa.JpaTransactionManager"
      p:entityManagerFactory-ref="entityManagerFactory"
      p:dataSource-ref="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:3306/qpdb?zeroDateTimeBehavior=convertToNull"/>
    <property name="username" value="root"/>
    <property name="password" value=""/>
</bean>

<tx:annotation-driven transaction-manager="txManager" />

</beans>

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="myAppPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.myapp.entities.GenericUser</class>
<properties>
  <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/qpdb?zeroDateTimeBehavior=convertToNull"/>
  <property name="javax.persistence.jdbc.password" value=""/>
  <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
  <property name="javax.persistence.jdbc.user" value="root"/>
  <!--<property name="eclipselink.weaving" value="static"/>-->
</properties>
</persistence-unit>
</persistence>

WelcomeController.java

package com.myapp.user.controllers;
import com.myapp.entities.GenericUser;
import java.math.BigInteger;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;

@Transactional(propagation=Propagation.SUPPORTS)
@Controller
public class WelcomeController {

@PersistenceContext
private EntityManager entityManager;

public WelcomeController() {
}

@RequestMapping({"/"})
public String showPublicPage(Map<String, Object> model) {
    GenericUser gu = new GenericUser();
    addUser(gu);
    return "welcome";
}

@Transactional(propagation= Propagation.REQUIRED,readOnly=false)
public void addUser(GenericUser gu) {
    gu.setUserID(BigInteger.ONE);
    gu.setEmail("asdfadf");
    entityManager.persist(gu);
}
}

GenericUser.java

package com.myapp.entities;

import java.io.Serializable;
import java.math.BigInteger;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;

@Entity
@Table(name="generic_user")
public class GenericUser implements Serializable {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "USER_ID")
private BigInteger userID;
@Column(name = "USERNAME")
private String username;
@Column(name = "EMAIL")
private String email;
@Column(name = "PASSWORD")
private String password;

public BigInteger getUserID() {
    return userID;
}

public void setUserID(BigInteger id) {
    this.userID = id;
}

public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

@Override
public int hashCode() {
    int hash = 0;
    hash += (userID != null ? userID.hashCode() : 0);
    return hash;
}

@Override
public boolean equals(Object object) {
    // TODO: Warning - this method won't work in the case the id fields are not set
    if (!(object instanceof GenericUser)) {
        return false;
    }
    GenericUser other = (GenericUser) object;
    if ((this.userID == null && other.userID != null) || (this.userID != null && !this.userID.equals(other.userID))) {
        return false;
    }
    return true;
}

@Override
public String toString() {
    return "com.myapp.entities.GenericUser[ id=" + userID + " ]";
}
}

I am starting tomcat with -javaagent:path/to/spring-agent-2.5.6.SEC03.jar

Tomcat Log

Jul 11, 2013 9:30:36 PM org.apache.catalina.core.ApplicationContext log

INFO: Destroying Spring FrameworkServlet 'dispatcher'

Jul 11, 2013 9:30:36 PM org.apache.catalina.core.ApplicationContext log

INFO: Closing Spring root WebApplicationContext

Jul 11, 2013 9:33:13 PM org.apache.catalina.core.ApplicationContext log

INFO: No Spring WebApplicationInitializer types detected on classpath

Jul 11, 2013 9:33:13 PM org.apache.catalina.core.ApplicationContext log

INFO: Initializing Spring root WebApplicationContext

Jul 11, 2013 9:33:13 PM 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.xml.XmlBeanDefinitionStoreException: Line 52 in XML document from ServletContext resource [/WEB-INF/applicationContext.xml] is invalid; nested exception is org.xml.sax.SAXParseException; lineNumber: 52; columnNumber: 6; The processing instruction target matching "[xX][mM][lL]" is not allowed.

at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:396)

at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:334)

at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)

at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:174)

at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:209)

at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:180)

at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:125)

at org.springframework.web.context.support.XmlWebApplicationContext.loadBeanDefinitions(XmlWebApplicationContext.java:94)

at org.springframework.context.support.AbstractRefreshableApplicationContext.refreshBeanFactory(AbstractRefreshableApplicationContext.java:131)

at org.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:522)

at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:436)

at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:385)

at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:284)

at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:111)

at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4779)

at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5273)

at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)

at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:895)

at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:871)

at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:615)

at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:649)

at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1585)

at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)

at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)

at java.util.concurrent.FutureTask.run(FutureTask.java:166)

at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)

at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)

at java.lang.Thread.run(Thread.java:722)

Caused by: org.xml.sax.SAXParseException; lineNumber: 52; columnNumber: 6; The processing instruction target matching "[xX][mM][lL]" is not allowed.

at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:198)

at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:177)

at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:441)

at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)

at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1388)

at com.sun.org.apache.xerces.internal.impl.XMLScanner.scanPIData(XMLScanner.java:675)

at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanPIData(XMLDocumentFragmentScannerImpl.java:980)

at com.sun.org.apache.xerces.internal.impl.XMLScanner.scanPI(XMLScanner.java:643)

at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:913)

at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:607)

at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:116)

at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:489)

at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:835)

at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:764)

at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:123)

at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:237)

at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:300)

at org.springframework.beans.factory.xml.DefaultDocumentLoader.loadDocument(DefaultDocumentLoader.java:75)

at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.doLoadBeanDefinitions(XmlBeanDefinitionReader.java:388)

... 27 more

Jul 11, 2013 9:33:13 PM org.apache.catalina.core.ApplicationContext log

INFO: Closing Spring root WebApplicationContext

Jul 11, 2013 9:33:13 PM org.apache.catalina.core.StandardContext listenerStop

SEVERE: Exception sending context destroyed event to listener instance of class org.springframework.web.context.ContextLoaderListener

java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext

at org.springframework.context.support.AbstractRefreshableApplicationContext.getBeanFactory(AbstractRefreshableApplicationContext.java:172)

at org.springframework.context.support.AbstractApplicationContext.destroyBeans(AbstractApplicationContext.java:1066)

at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:1040)

at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:988)

at org.springframework.web.context.ContextLoader.closeWebApplicationContext(ContextLoader.java:556)

at org.springframework.web.context.ContextLoaderListener.contextDestroyed(ContextLoaderListener.java:142)

at org.apache.catalina.core.StandardContext.listenerStop(StandardContext.java:4819)

at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5466)

at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232)

at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:160)

at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:895)

at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:871)

at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:615)

at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:649)

at org.apache.catalina.startup.HostConfig$DeployDescriptor.run(HostConfig.java:1585)

at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)

at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)

at java.util.concurrent.FutureTask.run(FutureTask.java:166)

at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)

at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)

at java.lang.Thread.run(Thread.java:722)

Jul 11, 2013 9:33:15 PM org.apache.catalina.core.ApplicationContext log

INFO: No Spring WebApplicationInitializer types detected on classpath

Jul 11, 2013 9:33:15 PM org.apache.catalina.core.ApplicationContext log

INFO: Initializing Spring root WebApplicationContext

Jul 11, 2013 9:33:18 PM org.apache.catalina.core.ApplicationContext log

INFO: Initializing Spring FrameworkServlet 'dispatcher'

Jul 11, 2013 9:34:32 PM org.apache.catalina.core.ApplicationContext log

INFO: Destroying Spring FrameworkServlet 'dispatcher'

Jul 11, 2013 9:34:32 PM org.apache.catalina.core.ApplicationContext log

INFO: Closing Spring root WebApplicationContext

Jul 11, 2013 9:34:34 PM org.apache.catalina.core.ApplicationContext log

INFO: No Spring WebApplicationInitializer types detected on classpath

Jul 11, 2013 9:34:34 PM org.apache.catalina.core.ApplicationContext log

INFO: Initializing Spring root WebApplicationContext

Jul 11, 2013 9:34:37 PM org.apache.catalina.core.ApplicationContext log

INFO: Initializing Spring FrameworkServlet 'dispatcher'

The application runs successfully and opens the 'welcome' view but data (GenericUser gu) does not persist...

3
Your applicationContext.xml have a problema on line 52. Probably the line: <tx:annotation-driven transaction-manager="txManager" /> You need to solve this first...renanleandrof
fixed that.. But now no persistence unit with name myAppPU can be found... persistence.xml goes into build/web/WEB-INF/classes/META-INF/ after build.. and i have specified persistenceXmlLocation in applicationContext.xml... Any ideas?PrawDG

3 Answers

1
votes

Probably p:persistenceXmlLocation="classpath*:META-INF/persistence.xml" this is wrong.. Try to put the xml on your WEB-INF/ folder and link it only as: persistenceXmlLocation="myxml.xml"

1
votes

Can you check if the dependency jars are available at correct location?

0
votes

Finally solved... Posting my solution for future reference..

I changed a lot of things before arriving at a working solution.. i don't remember exactly where was the problem.. so i am mentioning all the changes i made.

  1. Changed all xsd versions to 3.1.. (it may not have mattered)

  2. If you are using tomcat use spring-tomcat-weaver.jar for load time weaving as mentioned here.

  3. The main issue:

The Spring documentation states the following:

<tx:annotation-driven/> only looks for @Transactional on beans in the same application context it is defined in. This means that, if you put in a WebApplicationContext for a DispatcherServlet, it only checks for @Transactional beans in your controllers, and not your services. See Section 15.2, “The DispatcherServlet” for more information.

Since <tx:annotation-driven> is declared in applicationContext.xml all the classes that want to use @Transactional must be discovered in application context. So you need to specify <context:component-scan> in application context as well. But make sure you don't rediscover the controllers already specified in dispatcher-servlet.xml. You may use include-filter and exclude-filter elements within <context:component-scan> element to achieve this. Detailed explanation here.

You will not be able to use @Transactional in your controllers.. (you shouldn't IMO)