JPA Spring MVC configuration - spring

I am trying to connect to MySQL db using JPA and Spring. I am new to Spring.
I have added this to my config file where all the beans are defined:
<jee:jndi-lookup id="myEmf" jndi-name="hello-world"/>
<bean id="myEmf" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="myEmf"/>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
</bean>
Also Here is my persistence.xml, my persistence unit name is "hello-world".
<persistence-unit name="hello-world" transaction-type="RESOURCE_LOCAL">
org.hibernate.ejb.HibernatePersistence
When I try to instantiate the object, it throws me error.
Thanks,
Sara.
Update, error:
2012/08/28 23-25-56,993:8a4cd57fec4d0:ERR:ERROR[Error parsing XML: XML InputStream(1) A pseudo attribute name is expected.] 2012-08-28
23:25:56,994 ERROR
[org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/sara].[jsp]:704]
: Servlet.service() for servlet jsp threw exception
javax.persistence.PersistenceException: Unable to configure
EntityManagerFactory at
org.hibernate.ejb.Ejb3Configuration.configure(Ejb3Configuration.java:265)
at
org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:125)
at
javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:52)
at
javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:34)
at com.paypal.sara.sara.web.sample.mvc.Main.getPoints(Main.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:599) at
org.apache.commons.el.ArraySuffix.evaluate(ArraySuffix.java:314) at
org.apache.commons.el.ComplexValue.evaluate(ComplexValue.java:145) at
org.apache.commons.el.ExpressionEvaluatorImpl.evaluate(ExpressionEvaluatorImpl.java:263)
at
org.apache.commons.el.ExpressionEvaluatorImpl.evaluate(ExpressionEvaluatorImpl.java:190)

I found out what the problem was! Such a simple one but took my time.
I had <?xml version="1.0" encoding="UTF-8"> instead I should have had <?xml version="1.0" encoding="UTF-8"?>.
Thanks for your time.

Related

Trying to deploy a Spring Service on WSO2 Application Service

I'm trying to deploy a Spring Service in WSO2 Application Service. I did THIS tutorial and the app works fine on Eclipse, but when I try to deploy it on WSO2 I get this error:
Cannot load Spring beans. Please check the Spring context
configuration file and verify that the defined Spring beans exist in
the .jar file.
I unziped de .jar file and JdbcCustomerDAO class is there with all the others.
Spring context:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="customerDAO" class="com.mkyong.customer.dao.impl.JdbcCustomerDAO">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="url" />
<property name="username" value="username" />
<property name="password" value="password" />
</bean>
</beans>
I also tried to include spring and mysql-connector-java jars on /repository/components/extensions as says HERE.
EDIT:
ERROR {org.wso2.carbon.springservices.ui.SpringServiceMaker} - Cannot
load Spring beans. Please check the Spring context configuration file
and verify that the defined Spring beans exist in the .jar file.
{org.wso2.carbon.springservices.ui.SpringServiceMaker}
org.springframework.beans.factory.CannotLoadBeanClassException: Cannot
find class
[org.springframework.jdbc.datasource.DriverManagerDataSource] for bean
with name 'dataSource' defined in resource loaded through InputStream;
nested exception is java.lang.ClassNotFoundException:
org.springframework.jdbc.datasource.DriverManagerDataSource
Looks like it couldn't find spring-jdbc, so I added the jar to extensions but now I get this error:
ERROR {org.wso2.carbon.springservices.ui.SpringServiceMaker} - Cannot load
Spring beans. Please check the Spring context configuration file and
verify that the defined Spring beans exist in the .jar file.
{org.wso2.carbon.springservices.ui.SpringServiceMaker}
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'dataSource' defined in resource loaded
through InputStream: Instantiation of bean failed; nested exception is
org.springframework.beans.BeanInstantiationException: Could not
instantiate bean class
[org.springframework.jdbc.datasource.DriverManagerDataSource]:
Constructor threw exception; nested exception is
java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
I understand that commons.logging is also missing, but when I try to add it to extensions, WSO2 doesn't start. I get a lot of
Log4j:ERROR Could not instantiate...

org.hibernate.HibernateException: getNamedQuery is not valid without active transaction

I got an exception:
org.hibernate.HibernateException: getNamedQuery is not valid without active transaction org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:340)
$Proxy10.getNamedQuery(Unknown Source)
Here is my configuration:
...
<context:annotation-driven/>
<beans:bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<beans:property name="sessionFactory" ref="sessionFactory" />
</beans:bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
...
Also, I added context:annotation-driven since the tr:annotation-driven is not working, does <tx:annotation-driven/> use the transactionManager which obtain its own session from Hibernate?
I used my derived sessionFactory using Hibernate3 inside the annotated transaction, so how do I configure the Spring to do so?
The transaction manager has a dependency on session factory which it's using to manage transactions.
By adding <tx:annotation-driven /> you tell Spring how transactions are demarcated. In this case you can use annotations.
See the docs page how to use XML Schema-based configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- bean definitions here -->
</beans>

Inject JAXBContext into spring

I am trying to inject a JAXBContext into spring application context, by:
<bean id="jaxbContext" class="javax.xml.bind.JAXBContext" factory-method="newInstance">
<constructor-arg type="java.lang.Class" value="com.package.MyClassName"/>
</bean>
It throws an exception:
No matching factory method found: factory method 'newInstance'
And I also try :
<bean id="jaxbContext" class="javax.xml.bind.JAXBContext" factory-method="newInstance">
<constructor-arg type="java.lang.String" value="com.package"/>
</bean>
And It throws an an exception:
javax.xml.bind.JAXBException: "com.package" doesnt contain ObjectFactory.class or jaxb.index
I did put a jaxb.index file inside the package "com.package" and has a single line "MyClassName" in the file.
#Tomasz's answer is the solution I'd recommend, but if you want to stick with JAXBContext, then the reason your first example failed is that the static getInstance() method on JAXBContext doesn't take a single Class argument, it takes a vararg list of them. So you need to inject a list, not a single class:
<bean id="jaxbContext" class="javax.xml.bind.JAXBContext" factory-method="newInstance">
<constructor-arg value-type="java.lang.Class">
<list>
<value>com.package.MyClassName</value>
</list>
</constructor-arg>
</bean>
Have you tried Spring OXM? The last line is important, namespaces are for reference only:
<?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:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-1.5.xsd">
<oxm:jaxb2-marshaller id="marshaller" contextPath="com.package"/>
</beans>
See 8.4. XML Schema-based Configuration. Yu'll also need spring-oxm on your classpath.
this will resolve the problem for jaxb.index file or ObjectFactory problem in spring env. provide the value of the package where the classes are their which generate the xml
enter code here`
<bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="packagesToScan" >
<value>com.adarsh.spring.integration.entities</value>
</property>
</bean>`

persistence.xml - spring JPA

I have read dozens of articles, but I cant figure out, where the mistake is... it should be really simple. I'm trying to write app on appengine using Spring and JPA.
I am using JEE5 project (dont know if it matters)
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="persistenceUnitManager" class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
<property name="persistenceXmlLocation">
<value>classpath*:/META-INF/persistence.xml</value>
</property>
</bean>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="transactions-optional" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
The persistence.xml file is located in META-INF directory (ROOT/META-INF/persistence.xml)
<?xml version="1.0" encoding="UTF-8" ?>
<persistence 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_1_0.xsd" version="1.0">
<persistence-unit name="transactions-optional">
<provider>org.datanucleus.store.appengine.jpa.DatastorePersistenceProvider</provider>
<properties>
<property name="datanucleus.NontransactionalRead" value="true"/>
<property name="datanucleus.NontransactionalWrite" value="true"/>
<property name="datanucleus.ConnectionURL" value="appengine"/>
</properties>
</persistence-unit>
</persistence>
I still get this exception (i was trying to move meta-inf directory in src directory with no success, the exception was the same)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'genericJpaDAO': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected javax.persistence.EntityManagerFactory cz.cvut.fel.pupilbook.dao.support.jpa.GenericJpaDAO.entityManagerfactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/context/applicationContext.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: No Persistence provider for EntityManager named transactions-optional
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
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:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:844)
Thanks for help.
The anwer consists of two parts.
denisk was correct about the location of persistence.xml, it should be under src.
I was missing some dependencies to datanucleus (I thought they are provided). After adding them I got plenty of relevant exceptions. After resolving them everything works.
So - it was coincidence of two problem, each of them masked part of the other.

Websphere: JPA: java.lang.IllegalArgumentException: Object: Entity is not a known entity type

I'm trying to deploy an app using Eclipselink as my JPA Layer on IBM Websphere 7.0.0.9. While trying to do any CRUD operations, i get the following exception:
Caused by: java.lang.IllegalArgumentException: Object: Entity is not a known entity type.
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4199)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:380)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:37)
at java.lang.reflect.Method.invoke(Method.java:600)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:358)
at $Proxy93.persist(Unknown Source)
... 89 more
Another stack trace i see is :
Caused by: java.lang.ClassCastException: Entity incompatible with Entity
at o.u.d.dao.jpa.converter.impl.EntityBeanConvertorImpl.convertToModel(EntityBeanConvertorImpl.java:143)
... 223 more
My persistence.xml looks like:
<persistence-unit name="ds" transaction-type="JTA"> <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider> <jta-data-source>dsjta</jta-data-source> <class>Entity</class> <exclude-unlisted-classes>true</exclude-unlisted-classes> <properties> <property name="eclipselink.target-server" value="WebSphere_7" /> <property name="eclipselink.logging.level" value="OFF" /> <property name="eclipselink.ddl-generation" value="none" /> <property name="eclipselink.ddl-generation.output-mode" value="database" /> </properties> </persistence-unit>
My application context file looks like:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <property name="persistenceUnitName" value="ds"/> <property name="dataSource" ref="dataSource"/> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter"> <property name="showSql" value="false"/> <property name="generateDdl" value="false"/> </bean> </property> <property name="loadTimeWeaver"> <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/> </property> </bean>
Our VM is started with the -javaagent parameter specified and pointing to spring-agent.jar What could be the reason for these exceptions?
The issue here is there is no Spring LoadTimeWeaver for Websphere. When your application attempts to combine a Web-Tier application with the Spring managed EM while using the InstrumentationLoadTimeWeaver class cast exceptions result. EclipseLink supports weaving in all JPA 2 compliant containers but in this case Spring is acting as an intermediary and interfering with the weaving.
Until Spring has a LoadTimeWeaver for Websphere You will need to remove the InstrumentationLoadTimeWeaver and set the EclipseLink persistence.xml property "eclipselink.weaving" to false or use the Static weaver.

Resources