ComparablePath dynamically created property throws: illegal attempt to dereference collection

905 views
Skip to first unread message

Ely Schoenfeld

unread,
Oct 30, 2014, 6:04:58 PM10/30/14
to quer...@googlegroups.com

Hello all.

 

I'm adding RSQL/FIQL (query language for parametrized filtering of entries in RESTful APIs) to my Spring rest project in order to add custom filters from the front end.

 

 

The RSQL parser (https://github.com/jirutka/rsql-parser) forces me to use a “visitor” pattern. I managed to create a generic way to create the filter (BooleanExpression). In the generic method I use to create the filter I don’t have the actual sub-classes. For example the method has an “EntityPathBase<?>” parameter, instead of an actual “Q” class created automatically.

 

I managed to create a properties object like this:

 

    ComparablePath<Comparable> property = new ComparablePath(entidadClass, path, atributoAFiltrar);

 

Where:

    -entidadClass comes from the Entity where the filter is going to be applied to.

    -path comes from an EntityPathBase<?> that comes from the "Q" class generated automatically.

    -atributoAFiltrar is a string that comes from the RQSL parser containing the attribute to be operated on.

 

 

Then, I add the operations like this:

 

    if (RsqlParserOperators.EQUAL.equals(pNode.getOperator())) {

            filter = property.eq(primerArgumento);

    } else if (RsqlParserOperators.NOT_EQUAL.equals(pNode.getOperator())) {

            filter = property.ne(primerArgumento);

    ...

 

And finally (outside the generic method) I do:

 

    list  = xxxRepository.findAll(filter);

 

 

 

It works fine whenever the attribute to be filtered on belongs to the Entity itself. But if the Entity contains a Collection attribute and a filter is needed on an attribute of the contained entity it throws an exception.

 

For example a filter like “telefonos.telefono==tel1” applied to a “Sucursal” entity throws the following exception:

 

[illegal attempt to dereference collection [sucursal0_.id.telefonos] with element property reference [telefono]], [org.hibernate.QueryException: illegal attempt to dereference collection [sucursal0_.id.telefonos] with element property reference [telefono] [select count(sucursal)

from mx.i4b.timbrado.domain.entidades.Sucursal sucursal

where sucursal.activo = ?1 and sucursal.telefonos.telefono = ?2]]

 

The “Sucursal” entity has an attribute “telefonos” defined like this:

   

    @OneToMany(cascade=CascadeType.ALL)

    private Collection<Telefono> telefonos=new LinkedHashSet<Telefono>();

 

And the “Telefono” entity has a “telefono” attribute defined like this:

    @Column(name = "TELEFONO")

    private String telefono;

 

I have been looking for a way to manage this for days now.

Does anybody know how to add a join clause or an alias whenever a dot (“.”) is found in the attribute name?

Any ideas?

 

Using:

querydsl version: 3.4.2

querydsl apt-maven-plugin version: 1.0.9


Ely

timowest

unread,
Oct 31, 2014, 4:17:39 PM10/31/14
to quer...@googlegroups.com
Hi Ely.

An alternative way to access collection element properties is using any() paths like this:

sucursal.telefonos.any().telefono

This will be internally converted in a exists/subquery expression when used in a where clause.

Br,
Timo

Ely Schoenfeld

unread,
Nov 1, 2014, 10:06:04 AM11/1/14
to Querydsl on behalf of timowest
Thank you very much for your answer.

I tried it but maybe I'm doing something wrong.

I changed the received field name string from  "sucursal.telefonos.telefono" to "sucursal.telefonos.any().telefono"

So I used to have BooleanExpression like this:
[sucursal.activo = true && sucursal.telefonos.telefono = tel1]

And it became something like this:
[sucursal.activo = true && sucursal.telefonos.any().telefono = tel1]

(added the "sucursal.activo = true &&" filter just for reference, doesn't affect the result)

I now get an exception, and then a NullPointerExpression. I placed the whole exception information at the end. (I'm usig hibernate core 4.2.2.Final, by the way)


Following the idea of creating an exists sub-query, with reflection I now know when the field is a collection and it's content's object class. Then tried the following, but got exactly the same BolleanExpression I had at the beginning (when I wrote my first mail):

    ComparablePath<Comparable> propertyBase = new ComparablePath(entidadClass, path, dereferenceString);
    property = new ComparablePath(fieldArgClass, propertyBase, subAtributoAFiltrar);
    ...
    result = BooleanExpression.anyOf(property.eq(primerArgumento));

Where:
    -dereferenceString is everything before the last dot (".") in the received field name string.
    -fieldArgClass is the class of contained object in the collection
    -subAtributoAFiltrar is the rest of the received field name string.
    -primerArgumento is the value received string, (in this case "tel1")

Didn't matter at all that I used "BooleanExpression.anyOf"

Do you have any ideas?

Thank you again.


The exceptions I mentioned before are:

2014-11-01 06:12:58,287 ERROR [http-nio-8081-exec-2] (ErrorCounter.java:78) - <AST>:3:54: unexpected AST node: (
2014-11-01 06:12:58,290 ERROR [http-nio-8081-exec-2] (ErrorCounter.java:73) - <AST>:3:54: unexpected AST node: (
<AST>:3:54: unexpected AST node: (
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.addrExpr(HqlSqlBaseWalker.java:5022)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.addrExprLhs(HqlSqlBaseWalker.java:5337)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.addrExpr(HqlSqlBaseWalker.java:4917)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.expr(HqlSqlBaseWalker.java:1260)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.exprOrSubquery(HqlSqlBaseWalker.java:4639)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:4111)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2096)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2024)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:794)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:595)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:278)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:206)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:190)
    at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1796)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:342)
    at com.sun.proxy.$Proxy87.createQuery(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:262)
    at com.sun.proxy.$Proxy87.createQuery(Unknown Source)
    at com.mysema.query.jpa.impl.AbstractJPAQuery.createQuery(AbstractJPAQuery.java:128)
    at com.mysema.query.jpa.impl.AbstractJPAQuery.count(AbstractJPAQuery.java:84)
    at org.springframework.data.jpa.repository.support.QueryDslJpaRepository.findAll(QueryDslJpaRepository.java:118)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:358)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:343)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy109.findAll(Unknown Source)
    at mx.i4b.timbrado.service.entidades.SucursalServiceImpl.getSucursalesByEmisor(SucursalServiceImpl.java:158)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy110.getSucursalesByEmisor(Unknown Source)
    at mx.i4b.timbrado.service.ws.emisor.WsSucursalServiceImpl.listarSucursales(WsSucursalServiceImpl.java:280)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy117.listarSucursales(Unknown Source)
    at mx.i4b.timbrado.web.rest.SucursalController.listaSucursalesOrdenamientoYFiltrado(SucursalController.java:186)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilter(WebRequestTraceFilter.java:115)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$ApplicationContextFilterConfiguration$1.doFilterInternal(EndpointWebMvcAutoConfiguration.java:137)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration$MetricsFilter.doFilterInternal(MetricFilterAutoConfiguration.java:85)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:683)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1721)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1679)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)




java.lang.NullPointerException: null
    at org.hibernate.hql.internal.ast.HqlSqlWalker.lookupProperty(HqlSqlWalker.java:591)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.addrExpr(HqlSqlBaseWalker.java:4932)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.expr(HqlSqlBaseWalker.java:1260)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.exprOrSubquery(HqlSqlBaseWalker.java:4639)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.comparisonExpr(HqlSqlBaseWalker.java:4111)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2096)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.logicalExpr(HqlSqlBaseWalker.java:2024)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.whereClause(HqlSqlBaseWalker.java:794)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:595)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299)
    at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:278)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:206)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
    at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
    at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:190)
    at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
    at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
    at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1796)
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:328)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:342)
    at com.sun.proxy.$Proxy87.createQuery(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:262)
    at com.sun.proxy.$Proxy87.createQuery(Unknown Source)
    at com.mysema.query.jpa.impl.AbstractJPAQuery.createQuery(AbstractJPAQuery.java:128)
    at com.mysema.query.jpa.impl.AbstractJPAQuery.count(AbstractJPAQuery.java:84)
    at org.springframework.data.jpa.repository.support.QueryDslJpaRepository.findAll(QueryDslJpaRepository.java:118)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:358)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:343)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.data.jpa.repository.support.LockModeRepositoryPostProcessor$LockModePopulatingMethodIntercceptor.invoke(LockModeRepositoryPostProcessor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy109.findAll(Unknown Source)
    at mx.i4b.timbrado.service.entidades.SucursalServiceImpl.getSucursalesByEmisor(SucursalServiceImpl.java:158)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy110.getSucursalesByEmisor(Unknown Source)
    at mx.i4b.timbrado.service.ws.emisor.WsSucursalServiceImpl.listarSucursales(WsSucursalServiceImpl.java:280)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
    at com.sun.proxy.$Proxy117.listarSucursales(Unknown Source)
    at mx.i4b.timbrado.web.rest.SucursalController.listaSucursalesOrdenamientoYFiltrado(SucursalController.java:186)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:749)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.boot.actuate.trace.WebRequestTraceFilter.doFilter(WebRequestTraceFilter.java:115)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.boot.actuate.autoconfigure.EndpointWebMvcAutoConfiguration$ApplicationContextFilterConfiguration$1.doFilterInternal(EndpointWebMvcAutoConfiguration.java:137)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.springframework.boot.actuate.autoconfigure.MetricFilterAutoConfiguration$MetricsFilter.doFilterInternal(MetricFilterAutoConfiguration.java:85)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
    at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:683)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1721)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1679)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)



--
You received this message because you are subscribed to a topic in the Google Groups "Querydsl" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/querydsl/c5_HUWckml8/unsubscribe.
To unsubscribe from this group and all its topics, send an email to querydsl+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

timowest

unread,
Nov 1, 2014, 5:40:38 PM11/1/14
to quer...@googlegroups.com
Hi.

How did you create the any path? CollectionPath instances have it available via the any() method.

Br,
Timo
<p class="MsoNormal" style="margin-bottom:0.0001pt;line-height:normal;background-image:initial;background-repeat:in
...

Ely Schoenfeld

unread,
Nov 2, 2014, 10:12:10 PM11/2/14
to Querydsl on behalf of timowest
I have been using ComparablePath.

Tried for a couple of hours today but honestly didn't understand how to create the CollectionPath.

looked into https://github.com/querydsl/querydsl/blob/master/querydsl-core/src/main/java/com/mysema/query/types/path/BeanPath.java, to see if I could create my own CollectionPath based on that. Don't know why, but couldn't figure it out what are the queryType and PathInits. Maybe I'm not reading in the right place.

At the end I only have a "Q" Object as EntityPathBase<?>, the Entity Class, the attribute name as a String and the value as the needed kind of object (created through a callable method) as a List<Comparable<?>>. With Reflexion

Do you happen to have an easier example for me to look at, or maybe it would be easier if I add some more code, but I know I don't like people who say something like "Could you do my homework?" as if they where still in school. Even though, if you think it's ok, I could add here my "visitor" class for you to look at it (even if it's not very clean code since it's "in construction" and I'm very very new to querydsl, the RSQL parser and the visitor pattern for that matter).

I really appreciate your help.

Ely
 

--

timowest

unread,
Nov 3, 2014, 2:01:19 PM11/3/14
to quer...@googlegroups.com
Hi.

For dynamic deep Path construction PathBuilder is the right tool http://www.querydsl.com/static/querydsl/3.5.0/apidocs/com/mysema/query/types/path/PathBuilder.html

The methods of BeanPath are mostly meant to be used in the generated types, and not manually.

Your root path would be created via

PathBuilder<Entity> entity = new PathBuilder<>(Entity.class, "entity");

and other paths via the various get methods.

Alternative you can create CollectionPath also directly. For example using this constructor: public CollectionPath(Class<? super E> type, Class<Q> queryType, Path<?> parent, String property) {

queryType is the type that will be instantiated for the collectionPath.any() invocations.

Br,
Timo
...

Ely Schoenfeld

unread,
Nov 4, 2014, 2:43:10 PM11/4/14
to quer...@googlegroups.com
Hello again.

I've been trying for a while to get the "any()" part in the CollectionPath to work with a filter of "telefno = 'tel1'". Just couldn't make it work.

So I began trying to get a subquery to work and I'm still stuck also.

I hope you can take a look at the following excerpt of my code. I'm sure I haven't understand enough all the QueryDsl's "Path" concept. I bet the problem will be a simple and stupid mistake, but can't find it now.

After the code, I'm adding some log's information.

Thank you in advance.

        Class<?> entidadClass = (Class<?>) pParams.get("EntityClass");

        EntityPathBase<?> path = (EntityPathBase<?>) pParams.get("EntityPathBase");  // QueryDsl's "Q" generated class

        BooleanExpression result = null;
        String atributoAFiltrar = pNode.getSelector();  // RSQL Parser Node attribute to filter on
        List<Comparable<?>> listaArgumentos = new ArrayList<Comparable<?>>(pNode.getArguments());  // RSQL Parser Node argument's to filter with

        ...

                } else if (atributoAFiltrar.contains(".")) {
                    String origTmp = atributoAFiltrar;
                    dereferenceString = StringUtils.substringBefore(atributoAFiltrar,".");
                    atributoAFiltrar = StringUtils.substringAfter(atributoAFiltrar,".");

                    if (dereferenceString.length() > 0) {
                        try {
                            Field f = entidadClass.getDeclaredField(dereferenceString);
                            if (f.getType().isAssignableFrom(Collection.class)) {
                                isACollection = true;
                                subAtributoAFiltrar = atributoAFiltrar;

                                Type genericFieldType = f.getGenericType();

                                if(genericFieldType instanceof ParameterizedType){
                                    ParameterizedType aType = (ParameterizedType) genericFieldType;
                                    Type[] fieldArgTypes = aType.getActualTypeArguments();

                                    if (fieldArgTypes.length < 1) {
                                        String msg = "Received filter was: ["+origTmp+"]. Unable to determine collection contents class.";
                                        logger.error(msg);
                                        throw new EAppInternalException(ErrorCodesEnumInternal.I_GENERIC_ERR, msg);
                                    }

                                    if (fieldArgTypes.length > 1) {
                                        String msg = "Received filter was: ["+origTmp+"]. Filters on collection with more than one kind of objects is not permitted.";
                                        logger.error(msg);
                                        throw new EAppInternalException(ErrorCodesEnumInternal.I_NOT_PERMITED, msg);
                                    }
 
                                    fieldArgClass = (Class<?>) fieldArgTypes[0];
                                    logger.debug("fieldArgClass = " + fieldArgClass);
                                    logger.debug("subAtributoAFiltrar = " + subAtributoAFiltrar);
                                    
                                    property = new ComparablePath(entidadClass, path, dereferenceString);
                                    
                                    PathBuilder<?> entity = new PathBuilder<>(entidadClass, entidadClass.getSimpleName().toLowerCase());
                                    propertyCollection = entity.getCollection(subAtributoAFiltrar, fieldArgClass);
                                    
                                    collectionEntityPath = new EntityPathBase<Comparable>((Class<? extends Comparable>) fieldArgTypes[0], fieldArgClass.getSimpleName().toLowerCase());
                                    
/* HERE */                          propertyInCollection = new ComparablePath(fieldArgClass, propertyCollection /*collectionEntityPath*/, subAtributoAFiltrar);
                                }

        ...
 
        Comparable<?> primerArgumento = listaArgumentos.get(0);

        if (! isACollection) {
            property = new ComparablePath(entidadClass, path, atributoAFiltrar);
        }
        
        if (RsqlParserOperators.EQUAL.equals(pNode.getOperator())) {
            if (isACollection) {
                result = property.in(new JPASubQuery()
                    .from(collectionEntityPath)
                    .where(propertyInCollection.eq(primerArgumento))
                    .list(propertyInCollection));
            } else { 
                result = property.eq(primerArgumento);
            }
        } else if (RsqlParserOperators.IN.equals(pNode.getOperator())) {

        ...


The app log is:
2014-11-04 13:29:35.693 DEBUG 13092 --- [nio-8081-exec-2] m.i.t.s.entidades.SucursalServiceImpl    : BooleanExpression: [sucursal.activo = true && sucursal.telefonos in com.mysema.query.DefaultQueryMetadata@bcf8c742]
2014-11-04 13:29:35.749 ERROR 13092 --- [nio-8081-exec-2] m.i.t.s.entidades.SucursalServiceImpl    : Un atributo de los filtros recibidos [activo==true;telefonos.telefono==tel1] no exsite en la entidad solicitada o no tiene el tipo de datos correcto: [could not resolve property: telefono of: mx.i4b.timbrado.domain.entidades.Sucursal], [org.hibernate.QueryException: could not resolve property: telefono of: mx.i4b.timbrado.domain.entidades.Sucursal [select count(sucursal)
from mx.i4b.timbrado.domain.entidades.Sucursal sucursal
where sucursal.activo = ?1 and sucursal.telefonos in (select sucursal.telefono.telefono
from mx.i4b.timbrado.domain.entidades.Telefono telefono
where sucursal.telefono.telefono = ?2)]]


--------- If I change the line that begins with "/* HERE */" from propertyCollection to collectionEntityPath

The app log is:
2014-11-04 13:30:53.265 DEBUG 12824 --- [nio-8081-exec-2] m.i.t.s.entidades.SucursalServiceImpl    : BooleanExpression: [sucursal.activo = true && sucursal.telefonos in com.mysema.query.DefaultQueryMetadata@3cc1c361]
2014-11-04 13:30:53,323  WARN [http-nio-8081-exec-2] (SqlExceptionHelper.java:144) - SQL Error: 0, SQLState: 42601
2014-11-04 13:30:53,324 ERROR [http-nio-8081-exec-2] (SqlExceptionHelper.java:146) - ERROR: error de sintaxis en o cerca de «.»


The database (PostgreSql) log is:
2014-11-04 13:30:53 CST SENTENCIA:  select count(sucursal0_.id) as col_0_0_ from sucursal sucursal0_ cross join sucursal_telefonos telefonos1_, telefono telefono2_ where sucursal0_.id=telefonos1_.sucursal_id and telefonos1_.telefonos_id=telefono2_.id and sucursal0_.activo=$1 and (. in (select telefono3_.telefono from telefono telefono3_ where telefono3_.telefono=$2))


Ely.
Timo
 &nbsp
...

timowest

unread,
Nov 5, 2014, 2:33:46 PM11/5/14
to quer...@googlegroups.com
Hi.

The any() usage would be

    PathBuilder<?> entity = new PathBuilder<>(entidadClass, entidadClass.getSimpleName().toLowerCase());
    propertyCollection = entity.getCollection(subAtributoAFiltrar, fieldArgClass).any()

In the subquery case you will need to use

    new JPASubQuery().from(collectionPath, alias).where(alias. ...).exists()

Timo
...

Ely Schoenfeld

unread,
Nov 10, 2014, 3:32:25 PM11/10/14
to quer...@googlegroups.com
Hello Timo.

I couldn't implement either of these.

In the any usage how does it get filtered by the "tel1" value that comes in the filter text? :  [activo==true;telefonos.telefono==tel1]. As far as I can tell, the "entity.getCollection(subAtributoAFiltrar, fieldArgClass).any()" is not filtered by "propertyInCollection" path. Am I right?

In the JPASubQuery usage, couldn't find any way how to add the "alias" in the "from". I even upgraded to DslQuery version 3.5.0. Sorry if this is basic, I'm still a newbie.

Thank you for all your help.

...

Ely Schoenfeld

unread,
Jan 1, 2015, 6:30:54 PM1/1/15
to quer...@googlegroups.com
Hello  again Timo.

First of all: Happy New Year.

I left the project for some time, but now I'm trying to fix this again.

I tried some more the two hints you gave me about how to use "any()" syntax and how to use a subquery.

With the subquery I got a problem I don't know how to overcome. The entity "sucursal" has a many-to-many relationship with "telefono". When I do:

    PathBuilder<?> entity = new PathBuilder<>(fieldArgClass, fieldArgClass.getSimpleName().toLowerCase());

    property = new ComparablePath(entidadClass, path, dereferenceString);
    propertyCollection = entity.getCollection(atributoCollectionAFiltrar, fieldArgClass);

   
    collectionEntityPath = new EntityPathBase<Comparable>((Class<? extends Comparable>) fieldArgTypes[0],
            fieldArgClass.getSimpleName().toLowerCase());
   
    propertyInCollection = new ComparablePath(fieldArgClass, propertyCollection /*collectionEntityPath*/, atributoCollectionAFiltrar);

    result = new JPASubQuery()
        .from(collectionEntityPath)
        .where(propertyInCollection.eq(primerArgumento))
        .exists();

With something like "telefonos.telefono==tel1" on "sucursal", it creates a query like:

    select count(sucursal)
    from sucursal
    where exists (select 1
    from telefono
    where telefono = 'tel1')

But the "sucursal" table and "telefono" table are related through an intermediate table, so it always returns all the sucursal elements, since there does exist a "telefono" that meet the criteria. I hope I'm making myself clear.

I don't know how to obtain the intermediate table and/or how to create the relationships, since this should be a generic solution for any filter in a contained collection attribute of any entity.

So I think I should use the "any()" approach. I don't understand how to use it.

As you said erlier, if I where using directly the "Q" classes, what I need is to do something like "sucursal.telefonos.any().telefono". I asume I whould do something like 'sucursal.telefonos.any().telefono.eq("tel1")'.

Am I right?

But I'm trying to construct that in a "generic way".

Can't find how to do it.

For example:


    PathBuilder<?> entity = new PathBuilder<>(entidadClass, entidadClass.getSimpleName().toLowerCase());
    propertyCollection = entity.getCollection(dereferenceString, fieldArgClass);
     
    propertyInCollection = new ComparablePath(fieldArgClass, propertyCollection /*collectionEntityPath*/, atributoCollectionAFiltrar);

But then nothing I've tried even compiles:   
(Please excuse me if I'm doing silly things)

//    BooleanExpression result;
//    result = property.in(propertyCollection.any().when(propertyInCollection.eq(primerArgumento)));
//    result = property.in(propertyCollection.contains(propertyInCollection.eq(primerArgumento)));
//    result = property.in(propertyCollection.any().as("sub1")..and(propertyInCollection.eq(primerArgumento)));
//    result = propertyInCollection.eq(primerArgumento).in(propertyCollection.any());
//    result = propertyCollection.any().when(propertyInCollection.eq(primerArgumento));

I'm kind of "blind" here. I really don't understand what I need to do in order to get a query similar to:

    select count(*)
    from sucursal s, sucursal_telefonos st, telefono t
    where st.sucursal_id = s.id and st.telefonos_id = t.id
    and t.telefono = 'tel1'

or

    select count(sucursal)
    from sucursal
    where exists (select 1
    from sucursal_telefonos st, telefono t
    where st.sucursal_id = sucursal.id and st.telefonos_id = t.id
    and t.telefono = 'tel1')

But from the visitor, where you can receive an entity with a Many-to-Many/One-to-Many attribute filters

Any ideas?

Thank you very much for your patience.

Ely.
...

Ely Schoenfeld

unread,
Jan 6, 2015, 1:14:04 PM1/6/15
to quer...@googlegroups.com
Timo.

I hope you didn't waste much time on my last "cry out" for help.

Today, discussing it with a colleague, I compared the types returned on each step when doing it directly with the "Q" classes created by QueryDsl.
Something like this:

    filtros = filtros.and(qSucursal.telefonos.any().telefono.eq("tel1"));

I discovered the any() element returns a "QTelefono", and that happens to be a EntityPathBase<?> instead of a PathBuilder<?> as I had it declared.

Following the comparison of types and structure, I got to the solution.

I think I was banging my head to the same wall every time and ever took a step back and tried to see the big picture, I guess.

Thank you very much for all your help.

Following is the working code. Hope it helps someone else and that the Spanish words don't make it harder to understand.

I know I'm not an expert Java programmer, so any comments are very wellcome.

Ely.

    public BooleanExpression processComparisonNode(String pNombreNodo, ComparisonNode pNode,
            Map<String,Object> pParams, boolean multiValues) {

       
        BooleanExpression result = null;
        String atributoAFiltrar = pNode.getSelector();
       
        Class<?> entidadClass = (Class<?>) pParams.get("EntityClass");

        EntityPathBase<?> path = (EntityPathBase<?>) pParams.get("EntityPathBase");  // QueryDsl's "Q" generated class
       
        @SuppressWarnings("unused")
        Operator<java.lang.Boolean> ops;
       
        if (! RsqlParserOperators.operators().contains(pNode.getOperator())) {
            throw new EAppDataValidationException(ErrorCodesEnumDataValidation.DV_INVALID_DATA, "El operador recibido ["+pNode.getOperator()+"] no está definido.");
        }
       
        @SuppressWarnings("unchecked")
        Map<String, RsqlParserConversionTiposBase> conversionTipos = (Map<String, RsqlParserConversionTiposBase>) pParams.get("ConversionTipos");

       
        List<Comparable<?>> listaArgumentos = new ArrayList<Comparable<?>>(pNode.getArguments());  // RSQL Parser Node argument's to filter with

        String dereferenceString = "";
        String atributoAFiltrarOrig = atributoAFiltrar;
        boolean isACollection = false;
        Class<?> fieldArgClass = null;
        ComparablePath<Comparable<?>> property = null;
        EntityPathBase<?> collectionEntityPath = null;
        try {
           
            int cnt = 0;
            boolean salir = (! atributoAFiltrar.contains("."));
            do {  // to check received attribute once without splitting at "." character and once already splitted (only when it was not found in the previous loop iteration)
               
                cnt++;
               
                logger.debug("(cnt es: "+cnt+", salir es: "+(salir ? "true" : "false")+") dereferenceString: " + dereferenceString);
                logger.debug("(cnt es: "+cnt+", salir es: "+(salir ? "true" : "false")+") atributoAFiltrar: " + atributoAFiltrar);
               
                for (Map.Entry<String, RsqlParserConversionTiposBase> entry : conversionTipos.entrySet())
                {
                    //System.out.println(entry.getKey() + "/" + entry.getValue());
                    if ((entry != null)
                            && (entry.getValue() != null)
                            && (entry.getValue().getArgAdicional() != null)
                            && (entry.getValue().getArgAdicional().equals(atributoAFiltrar))
                            && (! entry.getKey().equals(atributoAFiltrar))) {
                        logger.debug("Se reemplaza el atributo recibido ["+atributoAFiltrar+"] por el real ["+entry.getKey()+"]");
                        atributoAFiltrar = entry.getKey();
                        salir = true;
                        break;
                    }
                }
               
                if (conversionTipos.containsKey(atributoAFiltrar)) {
                    salir = true;
                    RsqlParserConversionTiposBase convertidor = conversionTipos.get(atributoAFiltrar);
                       
                    for (ListIterator<Comparable<?>> iterator = listaArgumentos.listIterator(); iterator.hasNext();) {
                        Comparable<?> elemento = iterator.next();
                        String argStrTmp = (String) elemento;
                        convertidor.setArg(argStrTmp);
                        try {
                            Comparable<?> comparableTmp = (Comparable<?>) convertidor.call();
                            iterator.set(comparableTmp);
                        } catch (Exception e) {
                            throw new EAppDataValidationException(ErrorCodesEnumDataValidation.DV_INVALID_DATA, e.getMessage(), e);

                        }
                    }
                   
                } else if (atributoAFiltrar.contains(".")) {
                   
                    dereferenceString = StringUtils.substringBefore(atributoAFiltrar,".");
                    atributoAFiltrar = StringUtils.substringAfter(atributoAFiltrar,".");

                    logger.debug("origTmp = " + atributoAFiltrarOrig);
                    logger.debug("dereferenceString = " + dereferenceString);
                    logger.debug("atributoAFiltrar = " + atributoAFiltrar);


                    if (dereferenceString.length() > 0) {
                        try {
                            Field f = entidadClass.getDeclaredField(dereferenceString);
                            if (f.getType().isAssignableFrom(Collection.class)) {
                                isACollection = true;
                                logger.debug("ES UN ATRIBUTO DE TIPO COLECCIÓN");

                                Type genericFieldType = f.getGenericType();

                                if(genericFieldType instanceof ParameterizedType){
                                    ParameterizedType aType = (ParameterizedType) genericFieldType;
                                    Type[] fieldArgTypes = aType.getActualTypeArguments();

                                    if ((fieldArgTypes == null) || (fieldArgTypes.length < 1)) {
                                        String msg = "Solicitado filtrar por ["+atributoAFiltrarOrig+"]. No fue posible determinar el tipo de objetos contenidos en la colección.";

                                        logger.error(msg);
                                        throw new EAppInternalException(ErrorCodesEnumInternal.I_GENERIC_ERR, msg);
                                    }

                                    if (fieldArgTypes.length > 1) {
                                        String msg = "Solicitado filtrar por ["+atributoAFiltrarOrig+"]. No está permitido filtrar dentro de un atributo de tipo colección con más de un tipo de objeto.";

                                        logger.error(msg);
                                        throw new EAppInternalException(ErrorCodesEnumInternal.I_NOT_PERMITED, msg);
                                    }
                                   
                                    fieldArgClass = (Class<?>) fieldArgTypes[0];
                                   
                                  PathBuilder<?> entity = new PathBuilder<>(entidadClass, entidadClass.getSimpleName().toLowerCase());
                                  collectionEntityPath = entity.getCollection(dereferenceString, fieldArgClass).any();
                                }
                            } else {
                                logger.debug("No es un atributo de tipo colección");
                            }
                        } catch (NoSuchFieldException e) {
                            e.printStackTrace();
                        }
                    }
                    ///////////////////////////////////////////////////////////////////////
                }

            } while (cnt < 2 && !salir);
           
        } finally {
            if (dereferenceString.length() > 0) {
                atributoAFiltrar = dereferenceString + "." + atributoAFiltrar;
            }
        }
       
       
        if (listaArgumentos.size() > 0) {
           
            if (isACollection) {
                if (fieldArgClass == null) {
                    String msg = "Solicitado filtrar por ["+atributoAFiltrarOrig+"]. No fue posible determinar el tipo de objetos contenidos en la colección.";

                    logger.error(msg);
                    throw new EAppInternalException(ErrorCodesEnumInternal.I_GENERIC_ERR, msg);
                }
                property = new ComparablePath(fieldArgClass, collectionEntityPath, atributoAFiltrar);
            } else {

                property = new ComparablePath(entidadClass, path, atributoAFiltrar);
            }
           
            Comparable<?> primerArgumento = listaArgumentos.get(0);
           
            if (RsqlParserOperators.EQUAL.equals(pNode.getOperator())) {
                ops = Ops.EQ;
                if (primerArgumento == null) {
                    result = property.isNull();

                } else {
                    result = property.eq(primerArgumento);
                }
            } else if (RsqlParserOperators.IN.equals(pNode.getOperator())) {
                ops = Ops.IN;
                result = property.in(listaArgumentos);
            } else if (RsqlParserOperators.GREATER_THAN_OR_EQUAL.equals(pNode.getOperator())) {
                ops = Ops.GOE;
                validaNotNull(atributoAFiltrarOrig, primerArgumento, pNode.getOperator());
                result = property.goe(primerArgumento);
            } else if (RsqlParserOperators.GREATER_THAN.equals(pNode.getOperator())) {
                ops = Ops.GT;
                validaNotNull(atributoAFiltrarOrig, primerArgumento, pNode.getOperator());
                result = property.gt(primerArgumento);
            } else if (RsqlParserOperators.LESS_THAN_OR_EQUAL.equals(pNode.getOperator())) {
                ops = Ops.LOE;
                validaNotNull(atributoAFiltrarOrig, primerArgumento, pNode.getOperator());
                result = property.loe(primerArgumento);
            } else if (RsqlParserOperators.LESS_THAN.equals(pNode.getOperator())) {
                ops = Ops.LT;
                validaNotNull(atributoAFiltrarOrig, primerArgumento, pNode.getOperator());
                result = property.lt(primerArgumento);
            } else if (RsqlParserOperators.NOT_EQUAL.equals(pNode.getOperator())) {
                ops = Ops.NE;
                if (primerArgumento == null) {
                    result = property.isNotNull();
                } else {
                    result = property.ne(primerArgumento);
                }
            } else if (RsqlParserOperators.NOT_IN.equals(pNode.getOperator())) {
                ops = Ops.NOT_IN;
                result = property.notIn(listaArgumentos);
            }
           
        } else {
            validaNotNull(atributoAFiltrarOrig, null, pNode.getOperator());
        }
       
        return result;
       
    }

    private void validaNotNull(String pAtributoAFiltrarOriginal,
            Comparable<?> pArg, ComparisonOperator pOp) {
        if (pArg == null) {
            throw new EAppDataValidationException(ErrorCodesEnumDataValidation.DV_INVALID_DATA,
                    "El argumento recibido para el atributo ["+pAtributoAFiltrarOriginal+"] dió null al ser interpretado y no está "
                            + "implementado el manejo de null's para el operador ["+pOp+"]");
...

timowest

unread,
Jan 6, 2015, 3:41:30 PM1/6/15
to quer...@googlegroups.com
Hi Ely.

Happy new year to you too! I was on holidays until now and just catching up with the Querydsl google group messages now.

Good that you were able to find a solution. Your code is indeed a bit difficult to follow because of the mix of languages.

Br,
Timo
...
Reply all
Reply to author
Forward
0 new messages