QueryInvalidParametersException: Query has parameter "surveyId" supplied at execution yet the query doesnt make use of this parameter - jpa

#NamedQueries({
#NamedQuery(name="surveyResponse.getAverageRatings", query="SELECT AVG(ratings) FROM SurveyResponse surveyResponse WHERE surveyResponse.customerSurvey.surveyId = :surveyId"),
#NamedQuery(name="surveyResponse.getBySurvey", query = "SELECT FROM SurveyResponse surveyResponse WHERE surveyResponse.customerSurvey.surveyId = :surveyId")})
public class SurveyResponse implements Serializable {
#Id #GeneratedValue(strategy=GenerationType.SEQUENCE,
generator="SURVEY_RESPONSE_SEQUENCE")
#Column(name="SURVEYRESPONSEID")
private long surveyResponseId;
#ManyToOne(fetch=FetchType.EAGER, cascade=CascadeType.DETACH)
#JoinColumn(name="QNo", referencedColumnName="qNo")
private Questionair questionair;
#ManyToOne(fetch=FetchType.EAGER)
#JoinColumn(name="SURVEYID", referencedColumnName="surveyId")
private CustomerSurvey customerSurvey;
#Column(name="RATINGS")
private int ratings;
.....
}
persistence class:
public void submitSurveyResponse(List<CustomerSurvey> surveys) throws WorkServiceException {
EntityManager em = entityManagerFactory.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
for (CustomerSurvey survey : surveys) {
survey.setRespondedOn(Calendar.getInstance().getTime());
String surveyId = survey.getSurveyId();
Query query = em.createNamedQuery("surveyResponse.getAverageRatings").setParameter("surveyId", surveyId);
Double avgRating = (Double) query.getSingleResult();
BigDecimal bd = BigDecimal.valueOf(avgRating);
bd = bd.setScale(2, RoundingMode.HALF_UP);
avgRating = bd.doubleValue();
survey.setAvgRatings(avgRating);
CustomerSurvey mSurvey = em.merge(survey);
em.flush();
}
tx.commit();
em.clear();
em.close();
}
Cause :
2012-10-24 11:33:57,042[SpringOsgiExtenderThread-34]|DEBUG|DataNucleus.Transaction|147-org.datanucleus-3.1.1|Object "com.ge.dsp.iwork.entity.SurveyResponse#3a45cd18" (id="com.ge.dsp.iwork.entity.SurveyResponse:290") being evicted from transactional cache
2012-10-24 11:33:57,043[SpringOsgiExtenderThread-34]|DEBUG|DataNucleus.Transaction|147-org.datanucleus-3.1.1|Object "com.ge.dsp.iwork.entity.SurveyResponse#3a45cd18" (id="com.ge.dsp.iwork.entity.SurveyResponse:290") is not transactional
2012-10-24 11:33:57,043[SpringOsgiExtenderThread-34]|DEBUG|DataNucleus.Datastore|147-org.datanucleus-3.1.1|Closing PreparedStatement "org.datanucleus.store.rdbms.ParamLoggingPreparedStatement#3c9c008b"
2012-10-24 11:33:57,100[SpringOsgiExtenderThread-34]|DEBUG|DataNucleus.Transaction|147-org.datanucleus-3.1.1|Transaction created [DataNucleus Transaction, ID=Xid= ', enlisted resources=[]]
2012-10-24 11:33:57,101[SpringOsgiExtenderThread-34]|DEBUG|DataNucleus.Transaction|147-org.datanucleus-3.1.1|Transaction begun for ObjectManager org.datanucleus.ObjectManagerImpl#1326f1a6 (optimistic=true)
2012-10-24 11:33:57,104[SpringOsgiExtenderThread-34]|DEBUG|com.ge.dsp.kernel.bootloader.impl.DspServiceListener|153-dsp.kernel-0.8.0|MODIFIED
2012-10-24 11:33:57,104[SpringOsgiExtenderThread-34]|DEBUG|com.ge.dsp.kernel.bootloader.impl.DspServiceListener|153-dsp.kernel-0.8.0|ServiceReference [cxf-dosgi-ri-topology-manager] {org.osgi.service.remoteserviceadmin.EndpointListener}={endpoint.listener.scope=[(&(objectClass=org.apache.aries.blueprint.NamespaceHandler)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.aries.proxy.ProxyManager)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=javax.management.MBeanServer)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.karaf.features.FeaturesService)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.karaf.admin.AdminService)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.karaf.jaas.config.JaasRealm)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.karaf.jaas.config.KeystoreInstance)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.karaf.diagnostic.core.DumpProvider)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.karaf.features.FeaturesListener)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.karaf.jaas.config.KeystoreManager)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.karaf.jaas.modules.BackingEngineFactory)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.geronimo.osgi.registry.api.ProviderRegistry)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=javax.persistence.spi.PersistenceProvider)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.karaf.shell.commands.info.InfoProvider)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=com.ge.dsp.kernel.spi.DspServiceManagerService)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(&(component=jetty)(objectClass=org.apache.camel.spi.ComponentResolver))(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(&(component=bean)(objectClass=org.apache.camel.spi.ComponentResolver))(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(&(component=direct)(objectClass=org.apache.camel.spi.ComponentResolver))(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(&(component=log)(objectClass=org.apache.camel.spi.ComponentResolver))(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(&(language=simple)(objectClass=org.apache.camel.spi.LanguageResolver))(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.camel.spi.TypeConverterLoader)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=com.ge.dsp.kernel.spi.DspKernelPluggable)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=com.ge.dsp.dsi.clustering.DspClusterManager)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=com.ge.dsp.kernel.spi.DspWebServiceEnabler)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=com.ge.dsp.dsi.config.ConfigurationServiceFactory)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44)))],service.id=127}
2012-10-24 11:33:57,104[SpringOsgiExtenderThread-34]|DEBUG|com.ge.dsp.kernel.bootloader.impl.DspServiceListener|153-dsp.kernel-0.8.0|Found activities of NON-DSP services: ServiceReference [cxf-dosgi-ri-topology-manager] {org.osgi.service.remoteserviceadmin.EndpointListener}={endpoint.listener.scope=[(&(objectClass=org.apache.aries.blueprint.NamespaceHandler)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.aries.proxy.ProxyManager)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=javax.management.MBeanServer)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.karaf.features.FeaturesService)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.karaf.admin.AdminService)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.karaf.jaas.config.JaasRealm)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.karaf.jaas.config.KeystoreInstance)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.karaf.diagnostic.core.DumpProvider)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.karaf.features.FeaturesListener)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.karaf.jaas.config.KeystoreManager)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.karaf.jaas.modules.BackingEngineFactory)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.geronimo.osgi.registry.api.ProviderRegistry)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=javax.persistence.spi.PersistenceProvider)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.karaf.shell.commands.info.InfoProvider)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=com.ge.dsp.kernel.spi.DspServiceManagerService)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(&(component=jetty)(objectClass=org.apache.camel.spi.ComponentResolver))(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(&(component=bean)(objectClass=org.apache.camel.spi.ComponentResolver))(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(&(component=direct)(objectClass=org.apache.camel.spi.ComponentResolver))(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(&(component=log)(objectClass=org.apache.camel.spi.ComponentResolver))(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(&(language=simple)(objectClass=org.apache.camel.spi.LanguageResolver))(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=org.apache.camel.spi.TypeConverterLoader)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=com.ge.dsp.kernel.spi.DspKernelPluggable)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=com.ge.dsp.dsi.clustering.DspClusterManager)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=com.ge.dsp.kernel.spi.DspWebServiceEnabler)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44))), (&(objectClass=com.ge.dsp.dsi.config.ConfigurationServiceFactory)(!(endpoint.framework.uuid=eae78622-cdca-4196-ab13-f298ac516e44)))],service.id=127}
2012-10-24 11:33:57,177[SpringOsgiExtenderThread-34]|ERROR|org.springframework.osgi.extender.internal.activator.ContextLoaderListener|61-org.springframework.osgi.extender-1.2.1|Application context refresh failed (OsgiBundleXmlApplicationContext(bundle=dsp.dsp-iwork, config=osgibundle:/META-INF/spring/*.xml))
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testSubmitSurveyResponse' defined in URL [bundle://170.45:0/META-INF/spring/module-context.xml]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Query has parameter "surveyId" supplied at execution yet the query doesnt make use of this parameter
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1455)[54:org.springframework.beans:3.1.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)[54:org.springframework.beans:3.1.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)[54:org.springframework.beans:3.1.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)[54:org.springframework.beans:3.1.2.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)[54:org.springframework.beans:3.1.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)[54:org.springframework.beans:3.1.2.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)[54:org.springframework.beans:3.1.2.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:609)[54:org.springframework.beans:3.1.2.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918)[56:org.springframework.context:3.1.2.RELEASE]
at org.springframework.osgi.context.support.AbstractDelegatedExecutionApplicationContext.access$1600(AbstractDelegatedExecutionApplicationContext.java:69)[60:org.springframework.osgi.core:1.2.1]
at org.springframework.osgi.context.support.AbstractDelegatedExecutionApplicationContext$4.run(AbstractDelegatedExecutionApplicationContext.java:355)[60:org.springframework.osgi.core:1.2.1]
at org.springframework.osgi.util.internal.PrivilegedUtils.executeWithCustomTCCL(PrivilegedUtils.java:85)[60:org.springframework.osgi.core:1.2.1]
at org.springframework.osgi.context.support.AbstractDelegatedExecutionApplicationContext.completeRefresh(AbstractDelegatedExecutionApplicationContext.java:320)[60:org.springframework.osgi.core:1.2.1]
at org.springframework.osgi.extender.internal.dependencies.startup.DependencyWaiterApplicationContextExecutor$CompleteRefreshTask.run(DependencyWaiterApplicationContextExecutor.java:132)[61:org.springframework.osgi.extender:1.2.1]
at java.lang.Thread.run(Thread.java:662)[:1.6.0_34]
Caused by: java.lang.IllegalArgumentException: Query has parameter "surveyId" supplied at execution yet the query doesnt make use of this parameter
at org.datanucleus.api.jpa.JPAQuery.setParameter(JPAQuery.java:440)
at org.datanucleus.api.jpa.JPAQuery.setParameter(JPAQuery.java:56)
at com.ge.dsp.iwork.persistence.JpaWorkPersistence.submitSurveyResponse(JpaWorkPersistence.java:402)
at com.ge.dsp.iwork.impl.WorkServiceImpl.submitSurveyResponse(WorkServiceImpl.java:239)
at com.ge.dsp.iwork.test.WorkServiceTest.testSubmitSurveyResponse(WorkServiceTest.java:264)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)[:1.6.0_34]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)[:1.6.0_34]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)[:1.6.0_34]
at java.lang.reflect.Method.invoke(Method.java:597)[:1.6.0_34]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1581)[54:org.springframework.beans:3.1.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1522)[54:org.springframework.beans:3.1.2.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1452)[54:org.springframework.beans:3.1.2.RELEASE]
... 14 more
Caused by: org.datanucleus.store.query.QueryInvalidParametersException: Query has parameter "surveyId" supplied at execution yet the query doesnt make use of this parameter
at org.datanucleus.store.query.Query.applyImplicitParameterValueToCompilation(Query.java:881)
at org.datanucleus.store.query.AbstractJPQLQuery.compileInternal(AbstractJPQLQuery.java:310)
at org.datanucleus.store.rdbms.query.JPQLQuery.compileInternal(JPQLQuery.java:202)
at org.datanucleus.store.query.Query.setImplicitParameter(Query.java:799)
at org.datanucleus.store.rdbms.query.JPQLQuery.setImplicitParameter(JPQLQuery.java:147)
at org.datanucleus.api.jpa.JPAQuery.setParameter(JPAQuery.java:436)
... 25 more

I think, it is OK. But the one thing is referencedColumnName of CustomerSurvey.
Change to referencedColumnName="surveyId" to referencedColumnName="SERVEYID". Use uppercase letter because of you use the uppercase letter in CustomerSurvey entity(Previous Post).
You can reference here.
Update Answer :
When I check your query surveyResponse.getAverageRatings, there is a missing AVG(ratings). I think, it should AVG(surveyResponse.ratings).
SELECT AVG(surveyResponse.ratings) FROM SurveyResponse surveyResponse WHERE surveyResponse.customerSurvey.surveyId = :surveyId

Related

Search nested object with spring data, Illegal attempt to dereference path source

I use spring data jpa, I have these classe (each one have id... not displayed)
public class HOV{
#ManyToOne(optional = false, fetch = FetchType.LAZY, cascade = {CascadeType.MERGE, CascadeType.PERSIST})
#JoinColumn(name = "vehicle_type_id")
private VehicleTypes vehicleType;
...
}
public class VehicleTypes{
#OneToMany(mappedBy = "vehicleType")
private List<Vehicles> vehicles = new ArrayList<>();
}
so in hov repository, i tried to search by vehiclesId
List<HOV> findByVehicleTypeVehiclesId(Integer id);
Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'hOVRepository': Invocation of init
method failed; nested exception is java.lang.IllegalArgumentException:
Failed to create query for method public abstract java.util.List
com.lcm.repository.HOVRepository.findByVehicleTypeVehiclesId(java.lang.Integer)!
Illegal attempt to dereference path source [null.vehicleType.vehicles]
of basic type
In your situation, I think, is better to provide a query yourself, for example:
#Query("select h from HOV h join h.vehicleType vt left join vt.vehicles v where v.id = ?1")
List<HOV> findWithQuery(Integer vehicleId);

NullPointerException while using MongoTemplate in Spring boot

I have a collection named 'statusbynumbers' and I define the entity like this:
#Document(collection="statusbynumbers")
#Data
#AllArgsConstructor
#NoArgsConstructor
public class StatusByNumbersEntity {
#Id
private String id;
#Field("number")
private String number;
#Field("level")
private String
#Field("yat")
private double yat;
}
the key 'yat' is a double type in the db. But in my business logic, in some cases, 'yat' can be null. Then when I uses MongoTemplate.find() method, java.lang.NullPointerException: null was caused. The MongoTemplate.find() used in my code shown as below:
public class ReportsServiceImpl implements ReportsService {
#Resource
private MongoTemplate ReportsMongoTemplate;
#Override
public List<StatusByNumbersEntity> getNumbersByFilterLevel(String filterLevel) {
List<Integer> filterLevelList = FilterLevelModel.buildFilterLevel(filterLevel);
Criteria criteria = Criteria.where("level").in(filterLevelList);
Query query = new Query(criteria);
// java.lang.NullPointerException: null caused by the following code
List<StatusByNumbersEntity> numList = ReportsMongoTemplate.find(query,StatusByNumbersEntity.class);
...
}
The detailed error log shown as below
2017-10-10 02:47:06.475 ERROR org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is
java.lang.NullPointerException] with root cause
java.lang.NullPointerException: null
at sun.invoke.util.ValueConversions.unboxDouble(ValueConversions.java:139)
at com.test.application.entities.reports.numbersEntity_Accessor_22t0xt.setProperty(Unknown Source)
at org.springframework.data.mapping.model.ConvertingPropertyAccessor.setProperty(ConvertingPropertyAccessor.java:58)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$1.doWithPersistentProperty(MappingMongoConverter.java:291)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter$1.doWithPersistentProperty(MappingMongoConverter.java:279)
at org.springframework.data.mapping.model.BasicPersistentEntity.doWithProperties(BasicPersistentEntity.java:330)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:279)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:239)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:199)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:195)
at org.springframework.data.mongodb.core.convert.MappingMongoConverter.read(MappingMongoConverter.java:85)
at org.springframework.data.mongodb.core.MongoTemplate$ReadDbObjectCallback.doWith(MongoTemplate.java:2324)
at org.springframework.data.mongodb.core.MongoTemplate.executeFindMultiInternal(MongoTemplate.java:1969)
at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1787)
at org.springframework.data.mongodb.core.MongoTemplate.doFind(MongoTemplate.java:1770)
at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:644)
at org.springframework.data.mongodb.core.MongoTemplate.find(MongoTemplate.java:635)
How can i use the MongoTemplate.find() method even if the key "yat" can be null instead of double type to avoid this NullPointerException?
It's because you used a primitive type variable(double with lowercase 'd') for a nullable field.
You can't set null value for primitive data types(trows NullPointerException)
Replace 'double' with 'Double'
#Field("yat")
private Double yat;
Remember that you can't cast a null value to primitive data types either.
for when you had setters and getters replace the primitive type with non-primitive equivalent in them as well.
more details:
https://www.w3schools.com/java/java_data_types.asp

Error: Parameter value did not match expected type

I am trying to retrieve a USER from my database using the ID in the WHERE clause. However I am receiving an error and my program is failing.
This is the error I'm receiving when I run my program:
ERROR [org.jboss.as.ejb3.invocation] (default task-19)
JBAS014134: EJB Invocation failed on component CustomerServiceBeanImpl
for method public abstract package.name.entity.ICustomer
package.name.bean.CustomerServiceBean.getCustomerById(long):
javax.ejb.EJBException: java.lang.IllegalArgumentException:
Parameter value [19533] did not match expected type [package.name.entity.User (n/a)]
Note: [19533] is a test value I used.
This is the method that is having the error in the CustomerServiceBeanImpl.java:
#Override
public Customer getCustomerById (final long id)
{
return Customer.getById (this.em, id);
}
This is the method that's being called by the component CustomerServiceBeanImpl:
public static Customer getById (final EntityManager em, final long id)
{
for (final Customer c : em.createNamedQuery ("Customer.getById", Customer.class)
.setParameter ("id", id).setMaxResults (1).getResultList ())
{
return c;
}
return null;
}
The name query is this:
#NamedQuery (name = "Customer.getById",
query = "SELECT o FROM gnf.Customer o WHERE o.user = :id")
In the Customer.java class itself the relevant column is this one:
#ManyToOne (fetch = FetchType.LAZY)
#JoinColumn (name = "user_id")
private User user;
Doing a quick check of my ERD the "id" column in my "customer" table has a data type of BIGINT. However I'm not sure if that matters. (PostgreSQL database by the way.)
How can I fix this error?
The WHERE clause in your named query seems to be the problem. The attribute user in your Customer.class is of type User and your query expects it to be a type compatible to long.
...
Parameter value [19533] did not match expected type [package.name.entity.User ...
So if you need more help on this it would be great to see the complete entities User and Customer.
It is happening because in your database the parameter will be a #oneToOne object and you have to call the id inside the Object so you have to give the query as following :
"select user from User user where user.customer.id=:param"

JPA could not locate parameter while working with Stored procedure using Postgres

Any efforts in following problem would be highly appreciable.
I am trying to invoke stored procedure using #NamedStoredProcedureQueries
Here is the code snippet of my entity class
#Entity
#Table(name = "tx_oppertunity")
#NamedStoredProcedureQueries({ //
#NamedStoredProcedureQuery(name = "oppertunity.pastOppertunities", procedureName = "pastOppertunities",resultSetMappings="myMapping")})
#SqlResultSetMappings({
#SqlResultSetMapping(
name = "myMapping",
classes = #ConstructorResult(targetClass = DataHolder.class, columns = { #ColumnResult(name = "oppertunityid") }))
})
public class Oppertunity {
/** The oppertunity id. */
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "GEN_TX_OPPERTUNITY_SEQ")
#SequenceGenerator(allocationSize = 1, name = "GEN_TX_OPPERTUNITY_SEQ", sequenceName = "tx_oppertunity_seq")
#Column(name = "oppertunity_id", nullable = false, unique = true)
private Long oppertunity_id;
// other fields to follow
}
My stored procedure is written in postgres and looks like this.
CREATE OR REPLACE FUNCTION pastOppertunities()
RETURNS TABLE(oppertunityid integer) AS
$BODY$
BEGIN
RETURN QUERY select cast((opp.oppertunity_id) as integer) from tx_oppertunity opp where (opp.end_date)< (NOW() - INTERVAL '2 days');
END;
$BODY$
LANGUAGE plpgsql
Since I am using SQL Resultset mapping to map my result from stored procedure I have defined target class to hold those values as DataHolder.class which looks like this.
public class DataHolder implements Serializable{
private Integer oppertunityid;
/**
* #return the oppertunityid
*/
public Integer getOppertunityid() {
return oppertunityid;
}
/**
* #param oppertunityid the oppertunityid to set
*/
public void setOppertunityid(Integer oppertunityid) {
this.oppertunityid = oppertunityid;
}
public DataHolder(Integer oppertunityid) {
this.oppertunityid = oppertunityid;
}
}
However If I try to run the procedure using, JPA repository
#Procedure(name = "oppertunity.pastOppertunities")
public List<DataHolder> findPastOppertunities();
It gives me following exception,
11:51:07.200 [http-nio-8000-exec-7] ERROR o.a.c.c.C.[.[.[.[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Could not locate parameter registered using that position [1]; nested exception is java.lang.IllegalArgumentException: Could not locate parameter registered using that position [1]] with root cause
org.hibernate.procedure.NoSuchParameterException: Could not locate parameter registered using that position [1]
at org.hibernate.procedure.internal.ProcedureCallImpl.getParameterRegistration(ProcedureCallImpl.java:338) ~[hibernate-core-4.3.10.Final.jar:4.3.10.Final]
at org.hibernate.procedure.internal.ProcedureOutputsImpl.getOutputParameterValue(ProcedureOutputsImpl.java:68) ~[hibernate-core-4.3.10.Final.jar:4.3.10.Final]
at org.hibernate.jpa.internal.StoredProcedureQueryImpl.getOutputParameterValue(StoredProcedureQueryImpl.java:276) ~[hibernate-entitymanager-4.3.10.Final.jar:4.3.10.Final]
at org.springframework.data.jpa.repository.query.StoredProcedureJpaQuery.extractOutputValue(StoredProcedureJpaQuery.java:120) ~[spring-data-jpa-1.7.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryExecution$ProcedureExecution.doExecute(JpaQueryExecution.java:298) ~[spring-data-jpa-1.7.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:74) ~[spring-data-jpa-1.7.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:99) ~[spring-data-jpa-1.7.3.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:90) ~[spring-data-jpa-1.7.3.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:415) ~[spring-data-commons-1.9.3.RELEASE.jar:na]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:393) ~[spring-data-commons-1.9.3.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport$DefaultMethodInvokingMethodInterceptor.invoke(RepositoryFactorySupport.java:506) ~[spring-data-commons-1.9.3.RELEASE.jar:na]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) ~[spring-tx-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281) ~[spring-tx-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) ~[spring-tx-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136) ~[spring-tx-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) ~[spring-aop-4.1.7.RELEASE.jar:4.1.7.RELEASE]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:122) ~[spring-data-jpa-1.7.3.RELEASE.jar:na]
I am not sure what exactly I am missing here all parameters are specified correctly in #SQLREsultSetMapping and I added explicit typecast in procedure to compulsory return Integer value.
There was some post which was suggesting to use Entity manager to call stored procedure, after a long fight I made call using entity manager and it worked like a charm
public List<DataHolder> findPastOppertunities() {
// TODO Auto-generated method stub
StoredProcedureQuery spq = em.createStoredProcedureQuery("pastOppertunities");
List<DataHolder> resultList = spq.getResultList();
return resultList;
//return oppRepo.findPastOppertunities();
}
However I want to understand if its bug with JPA repositories, Why JPA is not able to map result from strored procedure using #SqlResultSetMapping.
Thanks,
Dipesh

Querying a collection of embeddable elements using eclipselink

I have the following JPA (2.0.2) entities:
Employee
#Entity
#Table(name = "T_EMPLOYEE")
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ElementCollection
#CollectionTable(name = "T_COMPETENCE")
private Set<Competence> competences;
// Getter and setters
}
and Competence
#Embeddable
public class Competence {
#JoinColumn(nullable = false)
#ManyToOne
private Skill skill;
// Getter and setters
}
(The skill entity shouldn't be important and is therefore omitted, so are various additional attributes.)
I'm using EclipseLink (2.2.0) to query my entities with a DAO. Now I'd like to use the following query:
public List<Employee> findBySkill(Skill skill) {
TypedQuery<Employee> query = getCurrentEntityManager().createQuery(
"SELECT e FROM Employee e JOIN e.competences c WHERE c.skill = :skill",
Employee.class);
query.setParameter("skill", skill);
return query.getResultList();
}
But it keeps throwing the following exception:
Caused by: Exception [EclipseLink-8030] (Eclipse Persistence Services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Error compiling the query [SELECT e FROM Employee e JOIN e.competences c WHERE c.skill = :skill], line 1, column 54: unknown state or association field [skill] of class [com.kaio.model.Competence].
at org.eclipse.persistence.exceptions.JPQLException.unknownAttribute(JPQLException.java:457)
at org.eclipse.persistence.internal.jpa.parsing.DotNode.validate(DotNode.java:88)
at org.eclipse.persistence.internal.jpa.parsing.Node.validate(Node.java:91)
at org.eclipse.persistence.internal.jpa.parsing.BinaryOperatorNode.validate(BinaryOperatorNode.java:34)
at org.eclipse.persistence.internal.jpa.parsing.EqualsNode.validate(EqualsNode.java:41)
at org.eclipse.persistence.internal.jpa.parsing.WhereNode.validate(WhereNode.java:34)
at org.eclipse.persistence.internal.jpa.parsing.ParseTree.validate(ParseTree.java:207)
at org.eclipse.persistence.internal.jpa.parsing.ParseTree.validate(ParseTree.java:183)
at org.eclipse.persistence.internal.jpa.parsing.ParseTree.validate(ParseTree.java:173)
at org.eclipse.persistence.internal.jpa.parsing.JPQLParseTree.populateReadQueryInternal(JPQLParseTree.java:110)
at org.eclipse.persistence.internal.jpa.parsing.JPQLParseTree.populateQuery(JPQLParseTree.java:84)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:216)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:187)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:139)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:123)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1376)
... 48 more
The message is pretty clear: It can't find the attribute Skill on my class Competence. But in my opinion there is no reason on that. Or do I have a wrong approach on my problem? How should I query in a List of embeddable objects?
Any help is appreciated.
Okay, this seems to be a bug and it has been solved in a later version of eclipse link. I updated the project to EclipseLink 2.4 and the problem disappeared.
Your Competence table will have a Skill.id field, so try:
"SELECT e FROM Employee e JOIN e.competences c WHERE c.skill.id = :skillId"
query.setParameter("skillId", skill.getId());