Discord.py error syntaxerror: invalid syntax - async-await

I’m coding a discord bot. I have a problem at the line 58. I don’t know what I need to do. I’m using repl.it to code my bot and Uptime robot to make my bot always online. My bot is in French, so don’t take care of the weird orthography. This is my code:.
main.py
#imports
from discord.ext import commands
from discord.ext.commands import Bot
from keep_alive import keep_alive
import discord
import os
import time
import random
import json
import choice
import youtube_dl
import datetime
import time
#clients
client = commands.client(command_prefix='-', help_command=None)
client = discord.Client()
#events
#client.event
async def on_ready():
activity = discord.Game(name="Amogus", type=1)
print("Amogus est en ligne!")
#commandes
#client.command()
async def ping(ctx):
await ctx.send('Pong! le message à été envoyé avec **{0}** ms'.format(round(bot.latency, 2)))
#client.command()
async def imposter(ctx):
await ctx.send(".    。    •\n゚  。   .\n.     。   。 . \n.   。      ඞ 。 .    •     •\n {message.author.mention} was An Impostor.  。 .\n0 Impostor remains     。\n   .   . ,    .  .")
#client.command()
async def help(ctx):
embed=discord.Embed(title="-help", description="Ici, vous pouvez voir les différentes commandes du bot! Si l'Usage contient [], ça veut dire que l'attribut n'est pas obligatoire. Si l'usage contient <>, ça veut dire que l'attribut est obligatoire", color=0xff0000)
embed.add_field(name="-help", value="Envoie ce message.\nUsage: -help [nom de la commande].", inline=False)
embed.add_field(name="-sus", value="Vérifie votre chance.\nUsage: -sus", inline=False)
embed.add_field(name="-coinflip", value="Fait un pile ou face.\nUsage: -coinflip", inline=False)
embed.add_field(name="-ping", value="Envoie le ping du bot.\nUsage: -ping\n", inline=False)
embed.add_field(name="-cheh", value="Envoie cheh avec un GIF.\nUsage: -cheh\n", inline=False)
embed.add_field(name="-dice", value="Lance des dés\nUsage: -dice <nombre de dés> <nombre de faces>\n", inline=False)
embed.set_footer(text="\nFaites -help [le nom de la commande] pour obtenir plus d’information sur une commande spécifique\n\nPar W1L7")
await ctx.send(embed=embed)
#client.command()
async def coinflip(ctx):
coinflip = ['pile', 'face']
await ctx.send(random.choice(coinflip))
#client.command()
async def cf(ctx):
coinflip = ['pile', 'face']
await ctx.send(random.choice(coinflip)
#client.command()
async def maps(ctx):
maps-au = ['https://static.wikia.nocookie.net/among-us-wiki/images/3/35/The_Skeld_map.png/revision/latest/scale-to-width-down/310?cb=20201111005126', 'https://static.wikia.nocookie.net/among-us-wiki/images/7/77/MIRA_HQ_map.png/revision/latest/scale-to-width-down/310?cb=20201111004730', 'https://static.wikia.nocookie.net/among-us-wiki/images/a/ab/Polus_map.png/revision/latest/scale-to-width-down/310?cb=20201111010008', 'https://static.wikia.nocookie.net/among-us-wiki/images/a/a1/The_Airship_map.png/revision/latest/scale-to-width-down/310?cb=20210419084345']
await ctx.send(random.choice(maps-au))
#client.command()
async def cheh(ctx):
await ctx.send("par le pouvoir du grand CHEHHHHHHHHHHHHH\nhttps://cdn.nerdschalk.com/wp-content/uploads/2020/10/tenor-26.gif")
#client.command(name='dice')
async def dice(ctx, number_of_dice: int, number_of_sides: int):
dice = [
str(random.choice(range(1, number_of_sides + 1)))
for _ in range(number_of_dice)
]
await ctx.send(', '.join(dice))
#client.command()
async def sus(ctx):
chance = ['sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus','sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus','sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus','sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus','sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus','sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus','sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus','sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus','sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'sus', 'when the imposter is sus\nhttps://www.youtube.com/watch?v=0bZ0hkiIKt0']
await ctx.send(random.choice(chance))
#mise en ligne
keep_alive()
client.run(os.getenv('TOKEN'))
.env
TOKEN=<I paste my token here>
Everything seems ok, but in the console, it is write this:
or
console
File main.py, line 58:
async def maps(ctx):
^
SyntaxError: invalid syntax

#client.command()
async def cf(ctx):
coinflip = ['pile', 'face']
await ctx.send(random.choice(coinflip)
Make sure to double-check your brackets.
client = commands.client(command_prefix='-', help_command=None)
client = discord.Client()
You are overwriting the variable here and the discord.Client() is not needed.
client = commands.Bot(command_prefix='-')
client.remove_command('help')
It Will work since commands.client doesn't seem to exist.

Related

How can I create bean for adviceChain?

I'm having a hard time converting this spring xml into java config. How can I define an adviceChain bean base on the below spring file.
This's my xml file:
<util:list id="adviceChain">
<ref bean="retryInterceptor"/>
</util:list>
<bean id="retryInterceptor" class="org.springframework.amqp.rabbit.config.StatelessRetryOperationsInterceptorFactoryBean">
<property name="messageRecoverer">
<bean class="customDiscardingMessageRecoverer" />
</property>
<property name="retryOperations" ref="retryTemplate" />
</bean>
<bean id="retryTemplate" class="org.springframework.retry.support.RetryTemplate">
<property name="backOffPolicy">
<bean class="org.springframework.retry.backoff.FixedBackOffPolicy">
<property name="backOffPeriod" value="3000" />
</bean>
</property>
<property name="retryPolicy">
<bean class="org.springframework.retry.policy.SimpleRetryPolicy">
<property name="maxAttempts" value="3" />
</bean>
</property>
</bean>
Here is what I tried:
#Bean
StatelessRetryOperationsInterceptorFactoryBean retryInterceptor() {
StatelessRetryOperationsInterceptorFactoryBean retryInterceptor = new StatelessRetryOperationsInterceptorFactoryBean();
DiscardingMessageRecoverer messageRecoverer = new DiscardingMessageRecoverer();
retryInterceptor.setMessageRecoverer(messageRecoverer);
retryInterceptor.setRetryOperations(retryTemplate());
return retryInterceptor;
}
#Bean
public RetryTemplate retryTemplate() {
RetryTemplate retryTemplate = new RetryTemplate();
FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
fixedBackOffPolicy.setBackOffPeriod(3000);
retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
retryPolicy.setMaxAttempts(3);
retryTemplate.setRetryPolicy(retryPolicy);
return retryTemplate;
#Bean
SimpleMessageListenerContainer listenerContainer(){
SimpleMessageListenerContainer listenerContainer = new SimpleMessageListenerContainer();
listenerContainer.setConnectionFactory(connectionFactory());
listenerContainer.setConcurrentConsumers(1);
listenerContainer.setAdviceChain(new Advice[] { (Advice) retryInterceptor() });
listenerContainer.setMessageListener(listenerAdapter());
listenerContainer.setQueues(queue());
return listenerContainer;
}
I receive org.springframework.amqp.rabbit.config.StatelessRetryOperationsInterceptorFactoryBean$$EnhancerBySpringCGLIB$$e3de830c cannot be cast to org.aopalliance.aop.Advice error at the line listenerContainer.setAdviceChain(new Advice[] { (Advice) retryInterceptor() });
I think this's because I didn't define AdviceChain bean like the spring xml file but so far I don't know how.
Edit StatelessRetryOperationsInterceptorFactoryBean like this :
#Bean
RetryOperationsInterceptor retryInterceptor() {
StatelessRetryOperationsInterceptorFactoryBean retryInterceptor = new StatelessRetryOperationsInterceptorFactoryBean();
DiscardingMessageRecoverer messageRecoverer = new DiscardingMessageRecoverer();
retryInterceptor.setMessageRecoverer(messageRecoverer);
retryInterceptor.setRetryOperations(retryTemplate());
return retryInterceptor.getObject();
}

More than one table found in namespace (, ) - with Spring, Hibernate and JPA

I’m using Spring 4 & Hibernate 5 with JPA and and Oracle Database, i have checked all my code and there is only one entity and a single table with the name LANGUE, My project still refuses to compile because of this error, Can someone help me please ….,
applicationContext.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:aop="http://www.springframework.org/schema/aop"
xmlns:faces="http://www.springframework.org/schema/faces"
xmlns:int-security="http://www.springframework.org/schema/integration/security"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:sec="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/integration/security http://www.springframework.org/schema/integration/security/spring-integration-security-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/faces http://www.springframework.org/schema/faces/spring-faces-2.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.xsd">
<context:component-scan base-package="com.collecteJ.crud" />
<context:component-scan base-package="com.collecteJ.crud.entities" />
<context:component-scan base-package="com.collecteJ.crud.test.entities" />
<context:component-scan base-package="com.collecteJ.crud.dao"/>
<context:component-scan base-package="com.collecteJ.crud.test.dao" />
<context:component-scan base-package="com.collecteJ.crud.service"/>
<context:component-scan base-package="com.collecteJ.crud.test.service"/>
<context:component-scan base-package="com.collecteJ.crud.test"/>
<context:component-scan base-package="com.collecteJ.business.compte"/>
<context:component-scan base-package="com.collecteJ.business.compte.impl" />
<context:component-scan base-package="com.collecteJ.business.service"/>
<context:component-scan base-package="com.collecteJ.business.service.impl" />
<context:component-scan base-package="com.collecteJ.business.test" />
<aop:config proxy-target-class="true"/>
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value> database.properties</value>
</property>
</bean>
<bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" >
<property name="driverClass" value="${jdbc.driverClassName}" />
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="user" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<property name="acquireIncrement" value="1"/>
<property name="maxPoolSize" value="10" />
<property name="maxStatements" value="0" />
<property name="minPoolSize" value="5" />
</bean>
<bean id="JDBCDataSource" 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>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" >
<property name="generateDdl" value="true" />
<property name="showSql" value="true"/>
</bean>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
<property name="dataSource" ref="pooledDataSource" />
<property name="persistenceUnitName" value="collecteJCrudSpringPU"/>
</bean>
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />
</beans>
persitence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="collecteJCrudSpringPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.collecteJ.crud.entities.Account</class>
<class>com.collecteJ.crud.entities.Agence</class>
<class>com.collecteJ.crud.entities.Collecte</class>
<class>com.collecteJ.crud.entities.Collecteur</class>
<class>com.collecteJ.crud.entities.CollecteurCompte</class>
<class>com.collecteJ.crud.entities.Compte</class>
<class>com.collecteJ.crud.entities.Comptecollecte</class>
<class>com.collecteJ.crud.entities.Devise</class>
<class>com.collecteJ.crud.entities.EtatCivil</class>
<class>com.collecteJ.crud.entities.Role</class>
<class>com.collecteJ.crud.entities.TypeTransaction</class>
<class>com.collecteJ.crud.entities.Utilisateur</class>
<class>com.collecteJ.crud.test.entities.Testtable</class>
</persistence-unit>
</persistence>
stack trace
run:
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in URL [file:/C:/Users/hpcc/Documents/GoldTelecom/NetBeansProjects/collecteJCrud/build/classes/com/collecteJ/crud/config/applicationContext.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: collecteJCrudSpringPU] Unable to build Hibernate SessionFactory
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1578)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:829)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
at com.collecteJ.crud.main.MainTest2.main(MainTest2.java:32)
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: collecteJCrudSpringPU] Unable to build Hibernate SessionFactory
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.persistenceException(EntityManagerFactoryBuilderImpl.java:954)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:882)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:318)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1637)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1574)
... 12 more
Caused by: org.hibernate.tool.schema.extract.spi.SchemaExtractionException: More than one table found in namespace (, ) : LANGUE
at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.processGetTableResults(InformationExtractorJdbcDatabaseMetaDataImpl.java:381)
at org.hibernate.tool.schema.extract.internal.InformationExtractorJdbcDatabaseMetaDataImpl.getTable(InformationExtractorJdbcDatabaseMetaDataImpl.java:279)
at org.hibernate.tool.schema.extract.internal.DatabaseInformationImpl.getTableInformation(DatabaseInformationImpl.java:105)
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigrationToTargets(SchemaMigratorImpl.java:162)
at org.hibernate.tool.schema.internal.SchemaMigratorImpl.doMigration(SchemaMigratorImpl.java:60)
at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:133)
at org.hibernate.tool.hbm2ddl.SchemaUpdate.execute(SchemaUpdate.java:101)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:470)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:879)
... 17 more
Java Result: 1
BUILD SUCCESSFUL (total time: 14 seconds)
Language.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.collecteJ.crud.entities;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* #author Cyrille benito
*/
#Entity
#Table(name = "LANGUE")
#NamedQueries({
#NamedQuery(name = "Langue.findAll", query = "SELECT l FROM Langue l"),
#NamedQuery(name = "Langue.findByCodeLangue", query = "SELECT l FROM Langue l WHERE l.codeLangue = :codeLangue"),
#NamedQuery(name = "Langue.findByReference", query = "SELECT l FROM Langue l WHERE l.reference = :reference"),
#NamedQuery(name = "Langue.findByLibelle", query = "SELECT l FROM Langue l WHERE l.libelle = :libelle"),
#NamedQuery(name = "Langue.findByFormatDateCourte", query = "SELECT l FROM Langue l WHERE l.formatDateCourte = :formatDateCourte"),
#NamedQuery(name = "Langue.findByFormatDateLongue", query = "SELECT l FROM Langue l WHERE l.formatDateLongue = :formatDateLongue"),
#NamedQuery(name = "Langue.findByFormatHeure", query = "SELECT l FROM Langue l WHERE l.formatHeure = :formatHeure"),
#NamedQuery(name = "Langue.findByFormatNumerique", query = "SELECT l FROM Langue l WHERE l.formatNumerique = :formatNumerique"),
#NamedQuery(name = "Langue.findByTaillePartieDecimale", query = "SELECT l FROM Langue l WHERE l.taillePartieDecimale = :taillePartieDecimale"),
#NamedQuery(name = "Langue.findBySeparateurMillier", query = "SELECT l FROM Langue l WHERE l.separateurMillier = :separateurMillier"),
#NamedQuery(name = "Langue.findBySeparateurPartieDecimale", query = "SELECT l FROM Langue l WHERE l.separateurPartieDecimale = :separateurPartieDecimale"),
#NamedQuery(name = "Langue.findByUtilisateuridModif", query = "SELECT l FROM Langue l WHERE l.utilisateuridModif = :utilisateuridModif"),
#NamedQuery(name = "Langue.findByUtilisateuridCrea", query = "SELECT l FROM Langue l WHERE l.utilisateuridCrea = :utilisateuridCrea"),
#NamedQuery(name = "Langue.findByDateCreation", query = "SELECT l FROM Langue l WHERE l.dateCreation = :dateCreation"),
#NamedQuery(name = "Langue.findByDateModification", query = "SELECT l FROM Langue l WHERE l.dateModification = :dateModification")})
public class Langue implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "CODE_LANGUE")
private String codeLangue;
#Basic(optional = false)
#Column(name = "REFERENCE")
private String reference;
#Basic(optional = false)
#Column(name = "LIBELLE")
private String libelle;
#Column(name = "FORMAT_DATE_COURTE")
private String formatDateCourte;
#Column(name = "FORMAT_DATE_LONGUE")
private String formatDateLongue;
#Column(name = "FORMAT_HEURE")
private String formatHeure;
#Column(name = "FORMAT_NUMERIQUE")
private String formatNumerique;
#Column(name = "TAILLE_PARTIE_DECIMALE")
private BigInteger taillePartieDecimale;
#Column(name = "SEPARATEUR_MILLIER")
private String separateurMillier;
#Column(name = "SEPARATEUR_PARTIE_DECIMALE")
private String separateurPartieDecimale;
#Column(name = "UTILISATEURID_MODIF")
private BigInteger utilisateuridModif;
#Column(name = "UTILISATEURID_CREA")
private BigInteger utilisateuridCrea;
#Column(name = "DATE_CREATION")
#Temporal(TemporalType.DATE)
private Date dateCreation;
#Column(name = "DATE_MODIFICATION")
#Temporal(TemporalType.DATE)
private Date dateModification;
public Langue() {
}
public Langue(String codeLangue) {
this.codeLangue = codeLangue;
}
public Langue(String codeLangue, String reference, String libelle) {
this.codeLangue = codeLangue;
this.reference = reference;
this.libelle = libelle;
}
public String getCodeLangue() {
return codeLangue;
}
public void setCodeLangue(String codeLangue) {
this.codeLangue = codeLangue;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getLibelle() {
return libelle;
}
public void setLibelle(String libelle) {
this.libelle = libelle;
}
public String getFormatDateCourte() {
return formatDateCourte;
}
public void setFormatDateCourte(String formatDateCourte) {
this.formatDateCourte = formatDateCourte;
}
public String getFormatDateLongue() {
return formatDateLongue;
}
public void setFormatDateLongue(String formatDateLongue) {
this.formatDateLongue = formatDateLongue;
}
public String getFormatHeure() {
return formatHeure;
}
public void setFormatHeure(String formatHeure) {
this.formatHeure = formatHeure;
}
public String getFormatNumerique() {
return formatNumerique;
}
public void setFormatNumerique(String formatNumerique) {
this.formatNumerique = formatNumerique;
}
public BigInteger getTaillePartieDecimale() {
return taillePartieDecimale;
}
public void setTaillePartieDecimale(BigInteger taillePartieDecimale) {
this.taillePartieDecimale = taillePartieDecimale;
}
public String getSeparateurMillier() {
return separateurMillier;
}
public void setSeparateurMillier(String separateurMillier) {
this.separateurMillier = separateurMillier;
}
public String getSeparateurPartieDecimale() {
return separateurPartieDecimale;
}
public void setSeparateurPartieDecimale(String separateurPartieDecimale) {
this.separateurPartieDecimale = separateurPartieDecimale;
}
public BigInteger getUtilisateuridModif() {
return utilisateuridModif;
}
public void setUtilisateuridModif(BigInteger utilisateuridModif) {
this.utilisateuridModif = utilisateuridModif;
}
public BigInteger getUtilisateuridCrea() {
return utilisateuridCrea;
}
public void setUtilisateuridCrea(BigInteger utilisateuridCrea) {
this.utilisateuridCrea = utilisateuridCrea;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public Date getDateModification() {
return dateModification;
}
public void setDateModification(Date dateModification) {
this.dateModification = dateModification;
}
#Override
public int hashCode() {
int hash = 0;
hash += (codeLangue != null ? codeLangue.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 Langue)) {
return false;
}
Langue other = (Langue) object;
if ((this.codeLangue == null && other.codeLangue != null) || (this.codeLangue != null && !this.codeLangue.equals(other.codeLangue))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.collecteJ.crud.entities.Langue[ codeLangue=" + codeLangue + " ]";
}
}
Try to change line
<property name="generateDdl" value="true" />
to:
<property name="generateDdl" value="false" />

spring unable to manage two entity manager

Hi all i ave an application with two different databases.
The first db is for our business app, the second belong to a framework we are using.
I have a manager in witch i need to access both dbs to perform some operations.
I configured my app with two entityManagerFactory, one for each datasource, and two transaction managers, one for each entityManagerFactory...
Here my configuration
my persistence.xml
<persistence version="1.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_1_0.xsd">
<persistence-unit name="ENPIM_BD_PU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<non-jta-data-source>jdbc/businessDataSource</non-jta-data-source>
<class>it.aicof.projects.enpim.persistence.entities.AccountingRecords</class>
.....
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.show_sql" value="false"/>
</properties>
</persistence-unit>
<persistence-unit name="ENPIM_SERV_PU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>it.aicof.projects.enpim.persistence.entities.Authusers</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.show_sql" value="false"/>
</properties>
</persistence-unit>
</persistence>
my app-context.xml
<context:annotation-config/>
<context:component-scan base-package="it.aicof.projects.*"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<bean id="dataSourceBusiness" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${profile.database.driverClassName}" />
<property name="jdbcUrl" value="jdbc:postgresql://${profile.database.hostname}:${profile.database.port}/${profile.database.business}" />
<property name="user" value="${profile.database.username}" />
<property name="password" value="${profile.database.password}" />
<!-- these are C3P0 properties -->
<property name="acquireIncrement" value="${c3p0.acquireIncrement}" />
<property name="initialPoolSize" value="${c3p0.initialPoolSize}" />
<property name="minPoolSize" value="${c3p0.minPoolSize}" />
<property name="maxPoolSize" value="${c3p0.maxPoolSize}" />
<property name="maxIdleTime" value="${c3p0.maxIdleTime}" />
</bean>
<bean id="dataSourceServ" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${profile.database.driverClassName}" />
<property name="jdbcUrl" value="jdbc:postgresql://${profile.database.hostname}:${profile.database.port}/${profile.database.serv}" />
<property name="user" value="${profile.database.username}" />
<property name="password" value="${profile.database.password}" />
<!-- these are C3P0 properties -->
<property name="acquireIncrement" value="${c3p0.acquireIncrement}" />
<property name="initialPoolSize" value="${c3p0.initialPoolSize}" />
<property name="minPoolSize" value="${c3p0.minPoolSize}" />
<property name="maxPoolSize" value="${c3p0.maxPoolSize}" />
<property name="maxIdleTime" value="${c3p0.maxIdleTime}" />
</bean>
<bean id="transactionManagerBusiness" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory">
<qualifier value="business" />
</bean>
<bean id="transactionManagerServ" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactoryServ">
<qualifier value="serv" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSourceBusiness"
p:jpaVendorAdapter-ref="jpaAdapter">
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
<property name="persistenceUnitName" value="ENPIM_BD_PU"></property>
</bean>
<bean id="entityManagerFactoryServ"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSourceServ"
p:jpaVendorAdapter-ref="jpaAdapter">
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
<property name="persistenceUnitName" value="ENPIM_SERV_PU"></property>
</bean>
<bean id="jpaAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
p:database="POSTGRESQL" p:showSql="false"/>
Here is the code i'm using
my dao
#PersistenceContext(unitName = "ENPIM_BD_PU")
protected EntityManager em;
#PersistenceContext(unitName = "ENPIM_SERV_PU")
protected EntityManager emServ;
....
public void edit(AddressBook addressBook) throws NonexistentEntityException, Exception {
try {
addressBook = em.merge(addressBook);
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).error("edit", ex);
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
Integer id = addressBook.getId();
if (findAddressBook(id) == null) {
throw new NonexistentEntityException("The addressBook with id " + id + " no longer exists.");
}
}
throw ex;
}
}
public void createBeneficiaryLoginAccount(String username, String password) throws Exception{
try {
Query q = emServ.createNativeQuery("INSERT INTO authusers(username, passwd, registrationdate, lastaccess, lastpasswordchange, active)" +
" VALUES (?, ?, ?, ?, ?, ?)");
q.setParameter(1, username);
q.setParameter(2, password);
q.setParameter(3, new Date());
q.setParameter(4, new Date());
q.setParameter(5, new Date());
q.setParameter(6, 1);
q.executeUpdate();
}catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).error("createBeneficiaryAccount", ex);
throw ex;
}
}
my manager
#Override
public void createBeneficiaryAccount(AddressBook addressBook, String password) {
String username = addressBook.getUsername();
try {
AddressBook ab = this.addressBookJpaDAO.findAddressBook(addressBook.getId());
ab.setUsername(username);
//creo l'utente sul db serv e gli assegno il ruolo di beneficiario
this.createBeneficiaryLoginAccount(username, password);
this.createBeneficiaryUsername(ab, password);
} catch (Throwable t) {
Logger.getLogger(this.getClass().getName()).error("", t);
}
}
#Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class, value = "serv")
private void createBeneficiaryLoginAccount(String username, String password) throws Throwable {
try {
//creo l'utente sul db serv e gli assegno il ruolo di beneficiario
this.addressBookJpaDAO.createBeneficiaryLoginAccount(username, password);
} catch (Throwable t) {
Logger.getLogger(this.getClass().getName()).error("createLoginAccount", t);
throw t;
}
}
#Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class, value = "business")
private void createBeneficiaryUsername(AddressBook addressBook, String password) throws Throwable {
try {
this.addressBookJpaDAO.edit(addressBook);
} catch (Throwable t) {
Logger.getLogger(this.getClass().getName()).error("createBeneficiaryUsername", t);
throw t;
}
}
when the method that uses the second entityManager is called i get the exception
2014-11-26 11:10:35,844 ERROR controllers.AddressBookJpaController - createBeneficiaryAccount
javax.persistence.TransactionRequiredException: Executing an update/delete query
at org.hibernate.jpa.spi.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
.....
and debugging the application i found that when we try to use the second entityManager we have this error
Exception occurred in target VM: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead
java.lang.IllegalStateException: Not allowed to create transaction on shared EntityManager - use Spring transactions or EJB CMT instead
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:198)
at com.sun.proxy.$Proxy145.getTransaction(Unknown Source)
at it.aicof.projects.enpim.persistence.controllers.AddressBookJpaController.createBeneficiaryLoginAccount(AddressBookJpaController.java:854)
i take a look on the web for some example but all have the same configuration as mine.
So.. why it's not working?
what's wrong?
thanks in advance
andrea
You're annotating #Transactional at a private method. That doesn't work with the Spring Aop Proxy Beans.
The quickest way is to set both methods to public
#Transactional("serv")
public void createBeneficiaryLoginAccount(String username, String password) throws Throwable {
try {
//creo l'utente sul db serv e gli assegno il ruolo di beneficiario
this.addressBookJpaDAO.createBeneficiaryLoginAccount(username, password);
} catch (Throwable t) {
Logger.getLogger(this.getClass().getName()).error("createLoginAccount", t);
throw t;
}
}
#Transactional("business")
public void createBeneficiaryUsername(AddressBook addressBook, String password) throws Throwable {
try {
this.addressBookJpaDAO.edit(addressBook);
} catch (Throwable t) {
Logger.getLogger(this.getClass().getName()).error("createBeneficiaryUsername", t);
throw t;
}
}
Or you might want to use AspectJ mode for AOP, but that is another layer of headaches IMHO.
See: Does Spring #Transactional attribute work on a private method?

Spring JMS transport the onSendAfterWrite in JMSReceiverConnection sends TextMessage[ID:<507866.1373381341790.0>, null] in response

The JMSRecieverConnection.send() flushes the response to transport output stream and returns the responseMessage to replyQueue. But the responseMessage is TextMessage[null, null]. Here is the code I am using, can anybody help in finding what is going wrong?
Consumer Configuration
JMS transport configuration,
<bean id="connectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate">
<ref bean="jndiTemplate" />
</property>
<property name="jndiName"
value="temp.connection" />
</bean>
<!-- Bean definition for jndi template -->
<bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory
</prop>
</props>
</property>
</bean>
<bean id="testQueue" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate">
<ref bean="jndiTemplate" />
</property>
<property name="jndiName"
value="temp.test.request" />
</bean>
<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory"/>
<bean id="defaultMessageListener" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
<property name="connectionFactory" ref="connectionFactory"/>
<property name="destination" ref="testQueue"/>
<property name="messageListener">
<bean class="org.springframework.ws.transport.jms.WebServiceMessageListener">
<property name="messageFactory" ref="messageFactory"/>
<property name="messageReceiver" ref="messageDispatcher"/>
</bean>
</property>
</bean>
<bean id="messageDispatcher" class="org.springframework.ws.soap.server.SoapMessageDispatcher">
<property name="endpointMappings">
<bean class="org.springframework.ws.server.endpoint.mapping.PayloadRootQNameEndpointMapping">
<property name="mappings">
<props>
<prop
key="{http://www.test.com/schema/mms/MSGM}ExampleRequest">exampleRequestEndpoint</prop>
</props>
</property>
<property name="interceptors">
<list>
<!-- ref bean="validatingInterceptor" /> -->
<bean class="org.springframework.ws.server.endpoint.interceptor.PayloadLoggingInterceptor" />
</list>
</property>
</bean>
</property>
</bean>
</beans>
Client code,
public static void main(String[] args) throws JMSException, Exception
{
String messageID = null;
String outString = null;
String qcfName = "temp.connection";
String qnameIn = "temp.test.request";
String qnameOut = "";
boolean verbose = false;
QueueSession session = null;
QueueConnection connection = null;
Context ctx = null;
QueueConnectionFactory qcf = null;
Queue inQueue = null;
Queue outQueue = null;
FileReader fr = new FileReader(new File("c:/myMsgm.xml"));
StringWriter sw = new StringWriter();
IOUtil.copyCompletely(fr, sw);
outString = sw.toString();
System.out.println("input : "+sw.toString());
Hashtable ht = new Hashtable();
ht.put("weblogic.jndi.replicateBindings", "false");
ht.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL, "t3://localhost:7001");
ctx = new InitialContext(ht);
qcf = (QueueConnectionFactory)ctx.lookup( qcfName );
inQueue = (Queue)ctx.lookup( qnameIn );
outQueue = (Queue)ctx.lookup( qnameOut );
connection = qcf.createQueueConnection();
connection.start();
boolean transacted = false;
session = connection.createQueueSession( transacted, Session.CLIENT_ACKNOWLEDGE);
QueueReceiver queueReceiver =null;
QueueSender queueSender = null;
time = Calendar.getInstance().getTime().toString();
for (int i = 0; i < 1; i++) {
queueSender = session.createSender(inQueue);
TextMessage outMessage = session.createTextMessage(outString);
Queue tempQueue = session.createTemporaryQueue();
outMessage.setJMSReplyTo(tempQueue);
queueSender.send(outMessage);
messageID = outMessage.getJMSMessageID();
System.out.println("Message ID : "+messageID);
// String selector = "JMSCorrelationID = '"+messageID+"'";
queueReceiver = session. createReceiver(tempQueue);
Message inMessage = queueReceiver.receive();
System.out.println("inMessage type : "+inMessage.getJMSType());
System.out.println("inMessage : "+inMessage);
if ( inMessage instanceof TextMessage ){
String replyString = ((TextMessage) inMessage).getText();
System.out.println("response message : "+ replyString);
}
}
System.out.println("start time : "+ time);
System.out.println("end time : "+ Calendar.getInstance().getTime());
sw.close();
queueReceiver.close();
queueSender.close();
session.close();
session = null;
connection.close();
connection = null;
}
Output
Message ID : ID:<507866.1373381334004.0> inMessage type : null
inMessage : TextMessage[ID:<507866.1373381341790.0>, null] response
message : null start time : Tue Jul 09 15:48:53 BST 2013 end time :
Tue Jul 09 15:49:01 BST 2013
Debugging result
The responseMessage is TextMessage[ID:<507866.1373381341790.0>, null] while sending reply to replyQueue in onSendAfterWrite of JMSReceiverConnection.
This problem is fixed using Spring-ws-core 1.5.4. This was a bug in spring-ws-core 1.5.1 and fixed from 1.5.3. Thanks to the people who have taken a look to resolve it.
reference: https://jira.springsource.org/browse/SWS-367
Prabhu

when I am running test cases that time entity manager is injected successfully but while running web app its throwing NullPointerException

I have a strange problem. I am injecting the entity manager using PersistenceContext using applicatioContext bean. But problem is that when I am running test cases that time entity manager is injected successfully but while running web app its throwing NullPointerException
this is abstractRepository where I am injecting entityManager
package com.ajit.retail.repository;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
public class AbstractRepository {
#PersistenceContext(type = PersistenceContextType.EXTENDED)
EntityManager entityManager;
}
this is my repository where I am using entity manager
package com.ajit.retail.repository;
import com.ajit.retail.exception.InvalidIdException;
import com.ajit.retail.model.Buyer;
import org.springframework.stereotype.Repository;
import javax.persistence.NoResultException;
#Repository
public class BuyerRepo extends AbstractRepository {
public Buyer getBuyer(String buyerName) throws InvalidIdException {
javax.persistence.Query buyerId = entityManager.createNativeQuery("select b.buyer_id from buyer b where b.name = :name").setParameter("name", buyerName);
Integer id;
try {
id = (Integer) buyerId.getSingleResult();
} catch (NoResultException e) {
return null;
}
return getBuyer(id);
}
public Buyer getBuyer(long buyerId) throws InvalidIdException {
Buyer buyer = entityManager.find(Buyer.class, buyerId); **====> NULL**
if (buyer == null) throw new InvalidIdException("Invalid Article ID");
return buyer;
}
}
this is my controller which is calling the repository method
package com.ajit.retail.web;
import com.sun.jersey.spi.inject.Inject;
import com.ajit.retail.exception.InvalidIdException;
import com.ajit.retail.model.Buyer;
import com.ajit.retail.repository.*;
import org.springframework.stereotype.Component;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
#Path("/buyer")
#Component
public class BuyerController {
#Inject
private BuyerRepo buyerRepo;
#GET
#Produces(MediaType.APPLICATION_JSON)
public Buyer searchFields() throws InvalidIdException {
String buyerId = "51";
Buyer buyer;
try {
buyer = buyerRepo.getBuyer(Long.parseLong(buyerId));
} catch (NumberFormatException e) {
buyer = buyerRepo.getBuyer(buyerId);
}
return buyer;
}
}
these are the unit tests which are passing
package com.ajit.retail.repository;
import com.ajit.retail.exception.InvalidIdException;
import org.hamcrest.core.IsEqual;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import static org.junit.Assert.assertThat;
public class BuyerRepoTest extends BaseRepository {
#Autowired
private BuyerRepo buyerRepo;
#Test
public void shouldGiveNameOfGivenBuyerId() throws InvalidIdException {
assertThat(buyerRepo.getBuyer(2).getName(), IsEqual.equalTo("SupervisorDLS"));
}
#Test(expected = InvalidIdException.class)
public void shouldThrowExceptionForInvalidBuyerId() throws InvalidIdException {
buyerRepo.getBuyer(-10);
}
}
this is the base repository
package com.ajit.retail.repository;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
#ContextConfiguration(locations = {"classpath:applicationContext.xml"})
public class BaseRepository extends AbstractTransactionalJUnit4SpringContextTests {
}
this is the 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" 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-2.5.xsd">
<context:annotation-config/>
<context:component-scan base-package="com.ajit.retail"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="org.postgresql.Driver"/>
<property name="url" value="jdbc:postgresql://localhost/retail"/>
<property name="username" value="retail_user"/>
<property name="password" value="password"/>
</bean>
<bean id="entityManager" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.ajit.retail"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect"/>
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManager"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
Please Help!
I solved this problem by replacing
<servlet>
<servlet-name>retail</servlet-name>
**<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>**
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.ajit.retail.web</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
with
<servlet>
<servlet-name>retail</servlet-name>
**<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>**
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>com.ajit.retail.web</param-value>
</init-param>
<init-param>
<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

Resources