Google app engine query with a list of string - java

I have a list of property values named 'token'. I am trying to filter an entity of kind
This is what i have tried.
List<String> tokens = getTokensFrom(invitations);
PersistenceManager pm = this.dataStoreService.getObjectDBConnection();
Query query = pm.newQuery(Invitations.class);
query.setFilter("tokens.contains(token)");
query.declareVariables(List.class.getName() + " tokens");
List<Invitations> invites = (List<Invitations>) query.execute(tokens);
But I'm getting the below error message.
Problem with query <SELECT FROM com.mypackage.shared.domainobjects.Invitations WHERE tokens.contains(token) VARIABLES java.util.List tokens>: Unsupported method <contains> while parsing expression: InvokeExpression{[VariableExpression{tokens}].contains(PrimaryExpression{token})}
com.google.appengine.datanucleus.query.DatastoreQuery$UnsupportedDatastoreFeatureException: Problem with query <SELECT FROM com.testbudha.shared.domainobjects.PublishedExam WHERE tokens.contains(token) VARIABLES java.util.Collection tokens>: Unsupported method <contains> while parsing expression: InvokeExpression{[VariableExpression{tokens}].contains(PrimaryExpression{token})}
at com.google.appengine.datanucleus.query.DatastoreQuery.newUnsupportedQueryMethodException(DatastoreQuery.java:993)
at com.google.appengine.datanucleus.query.DatastoreQuery.handleContainsOperation(DatastoreQuery.java:971)
at com.google.appengine.datanucleus.query.DatastoreQuery.addExpression(DatastoreQuery.java:830)
at com.google.appengine.datanucleus.query.DatastoreQuery.addFilters(DatastoreQuery.java:739)
at com.google.appengine.datanucleus.query.DatastoreQuery.compile(DatastoreQuery.java:248)
at com.google.appengine.datanucleus.query.JDOQLQuery.performExecute(JDOQLQuery.java:158)
at org.datanucleus.store.query.Query.executeQuery(Query.java:1789)
at org.datanucleus.store.query.Query.executeWithArray(Query.java:1666)
at org.datanucleus.api.jdo.JDOQuery.execute(JDOQuery.java:243)
I had a similar problem previously but it works because the filter criteria was the other way round i.e. this.token.contains(tokens) where 'token' was part of the entity and was of type List of String. But I'm not sure why this is not working. Can someone please help me?

You declare some variable called "tokens" yet pass in a parameter (presumably what you intended to be the tokens variable). A variable is not a parameter, they are different. Either use an explicit parameter, or an implicit parameter (with : prefix) as any decent JDO docs would tell you

Related

How to use JOOQ's parser to extract table names from SQL statements [duplicate]

Using the JOOQ parser API, I'm able to parse the following query and get the parameters map from the resulting Query object. From this, I can tell that there is one parameter, and it's name is "something".
However, I haven't been able to figure out how to determine that the parameter "something" is assigned to a column named "BAZ" and that column is part of the table "BAR".
Does the parser API have a way to get the table/column metadata associated to each parameter?
String sql = "SELECT A.FOO FROM BAR A WHERE A.BAZ = :something";
DSLContext context = DSL.using...
Parser parser = context.parser();
Query query = parser.parseQuery(sql);
Map<String, Param<?>> params = query.getParams();
Starting from jOOQ 3.16
jOOQ 3.16 introduced a new, experimental (as of 3.16) query object model API, which can be traversed, see:
The manual
A blog post about traversing jOOQ expression trees
Specifically, you can write:
List<QueryPart> parts = query.$traverse(
Traversers.findingAll(q -> q instanceof Param)
);
Or, to conveniently produce exactly the type you wanted:
Map<String, Param<?>> params = query.$traverse(Traversers.collecting(
Collectors.filtering(q -> q instanceof Param,
Collectors.toMap(
q -> ((Param<?>) q).getParamName(),
q -> (Param<?>) q
)
)
));
The Collectors.toMap() call could include a mergeFunction, in case you have the same param name twice.
Pre jOOQ 3.16
As of jOOQ 3.11, the SPI that can be used to access the internal expression tree is the VisitListener SPI, which you have to attach to your context.configuration() prior to parsing. It will then be invoked whenever you traverse that expression tree, e.g. on your query.getParams() call.
However, there's quite a bit of manual plumbing that needs to be done. For example, the VisitListener will only see A.BAZ as a column reference without knowing directly that A is the renamed table BAR. You will have to keep track of such renaming yourself when you visit the BAR A expression.

How to query Grakn with Java?

I went through the documentation of Java api to query Grakn database.
Grakn.Transaction readTransaction = session.transaction(GraknTxType.READ);
GetQuery query = Graql.match(var("p").isa("person")).limit(10).get();
Stream<ConceptMap> answers = query.withTx(readTransaction).stream();
answers.forEach(answer -> System.out.println(answer.get("p").id()));
It's printing id, but I want to see the data, the name associated with the person. I want to see the content inside the result. It's simply showing id.
The answers provided as the result of a Graql query, is a collection of the variables (and their values) as you have specified them in the query itself.
In this case, to get the name of instances of person, you'd include it in the query like so:
GetQuery query = Graql.match(var("p").isa("person").has("name", var("n"))).limit(10).get();
The Graql equivalent being match $p isa person, has name $n; get;.
Now you can use the methods available in the Concept API to retrieve information available on each variable.
In this case, variable n holds an attribute and you'd want to retrieve its value(), like so:
answers.forEach(answer -> System.out.println(answer.get("n").asAttribute().value()))

CrudRepository - Stored Procedure call is not working because of type/number of argument issue

I have JPA entity as
And then Repository as
Now, when I run it then I get following exception:
And stored procedure is:
It is running against Oracle database. Can someone please help me understand even though I have correct parameter numbers and type, still why I am getting this exception.
Please note: I do not have local environment so I cannot put a sample code, and please do not worry about class/method name, I tried to camouflage them so they may be inconsistent.
There is one more question that suppose I have 2 OUT parameters then how you I create my entity class, with one output parameter I know I can return String (or appropriate return type) but in case of 2 OUT parameters I do no know how to do it? I have read this article but it is only with 1 OUT parameter, and I couldn't find any article or post which explains for 2 OUT parameter. If someone has a code with 2 OUT parameter then it would be helpful.
Please try:
use the exact (db) names of procedure parameters:
#StoredProcedureParameter(name = "tbl_name" ...
#StoredProcedureParameter(name = "p_date" ...
#StoredProcedureParameter(name = "p_message" ...
or (alternatively) omit names completely (rely on position).
From StoredProcedureParameter javadoc:
The name of the parameter as defined by the stored procedure in the database. If a name is not specified, it is assumed that the stored procedure uses positional parameters.
Currently you can't have multiple OUT-parameters using spring-data, but (should be) no problem with standard JPA:
StoredProcedureQuery spq = em.createNamedStoredProcedureQuery("my_proc");
proc.setParameter("p_in", 1);
proc.execute();
Integer res1 = (Integer) proc.getOutputParameterValue("out1");
Integer res2 = (Integer) proc.getOutputParameterValue("out2");
see also: Spring Data JPA NamedStoredProcedureQuery Multiple Out Parameters

Unable to retrive Projection/Multi- Relantion field Requests.Custom_SFDCChangeReqID2 using versionone java sdk

I have been trying to retrieve information from querying a specific Asset(Story/Defect) on V1 using the VersionOne.SDK.Java.APIClient. I have been able to retrieve information like ID.Number, Status.Name but not Requests.Custom_SFDCChangeReqID2 under a Story or a Defect.
I check the metadata for:
https://.../Story?xsl=api.xsl
https://.../meta.V1/Defect?xsl=api.xsl
https://.../meta.V1/Request?xsl=api.xsl
And the naming and information looks right.
Here is my code:
IAssetType type = metaModel.getAssetType("Story");
IAttributeDefinition requestCRIDAttribute = type.getAttributeDefinition("Requests.Custom_SFDCChangeReqID2");
IAttributeDefinition idNumberAttribute = type.getAttributeDefinition("ID.Number")
Query query = new Query(type);
query.getSelection().add(requestCRIDAttribute);
query.getSelection().add(idNumberAttribute);
Asset[] results = v1Api.retrieve(query).getAssets();
String RequestCRID= result.getAttribute(requestCRIDAttribute).getValue().toString();
String IdNumber= result.getAttribute(idNumberAttribute).getValue().toString();
At this point, I can get some values for ID.Number but I am not able to retrieving any information for the value Custom_SFDCChangeReqID2.
When I run the restful query to retrieve information using a browser from a server standpoint it works and it does retrieve the information I am looking for. I used this syntax:
https://.../rest-1.v1/Data/Story?sel=Number,ID,Story.Requests.Custom_SFDCChangeReqID2,Story.
Alex: Remember that Results is an array of Asset´s, so I guess you should be accessing the information using something like
String RequestCRID= results[0].getAttribute(requestCRIDAttribute).getValue().toString();
String IdNumber= results[0].getAttribute(idNumberAttribute).getValue().toString();
or Iterate through the array.
Also notice that you have defined:
Asset[] results and not result
Hi thanks for your answer! I completely forgot about representing the loop, I was too focus on the retriving information part, yes I was actually using a loop and yes I created a temporary variable to check what I was getting from the query in the form
Because I was getting the variables one by one so I was only using the first record. My code works after all. It was just that What I was querying didn't contain any information of my use, that's why I was not finding any. Anyway thanks for your comment and observations

Consecutive named parameter problems in Hibernate (Spring HibernateTemplate)

I am trying to use named parameters to inject some strings into a query. I am using spring and hibernateTemplate, and and I am fairly new to Hibernate. I have gotten unnamed and named parameters to work in the past, but it seems as though when they are right next to each other they throw an error. I have made similar example code to my problem below (simplified to highlight the problem at hand). orderBy contains a string of a field and orderDirection contains ASC or DESC.
public List<HashMap<String, Object>> exampleList(String orderBy, String orderDirection) {
logger.debug(orderBy);
logger.debug(orderDirection);
final String queryString = "SELECT new map("+
"a.id AS id, "+
"a.name AS name, "+
"a.number AS number ) "+
"FROM Asset a "+
"ORDER BY :orderBy :orderDirection";
String[] parameterNames = {"orderBy", "orderDirection"};
Object[] parameterValues = {orderBy, orderDirection};
List<HashMap<String, Object>> results = (List<HashMap<String, Object>>) hibernateTemplate.find(queryString, parameterNames, parameterValues);
return results;
}
The console debugs my parameters:
DEBUG: com.myOrg.myProject.asset.AssetDAO - a.id
DEBUG: com.myOrg.myProject.asset.AssetDAO - desc
And I know this query would run fine on its own, as I have tested it with putting the values directly into the query string. I know that this is bad practice and can expose me to injection which is why I am not doing that.
The error I get is as follows (stack trace is shortened for ease of reading, but this is the only error and I can provide full stack trace upon request):
SEVERE: Servlet.service() for servlet dmat3 threw exception
org.hibernate.hql.ast.QuerySyntaxException: unexpected token: : near line 1, column 118 [SELECT new map(a.id AS id, a.name AS name, a.number AS number ) FROM com.gsipt.dmat3.asset.Asset a ORDER BY :orderBy :orderDirection]
at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:31)
at org.hibernate.hql.ast.QuerySyntaxException.convert(QuerySyntaxException.java:24)
at org.hibernate.hql.ast.ErrorCounter.throwQueryException(ErrorCounter.java:59)
at org.hibernate.hql.ast.QueryTranslatorImpl.parse(QueryTranslatorImpl.java:258)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:157)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:111)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:56)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:112)
at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1623)
at org.springframework.orm.hibernate3.HibernateTemplate$30.doInHibernate(HibernateTemplate.java:914)
at org.springframework.orm.hibernate3.HibernateTemplate$30.doInHibernate(HibernateTemplate.java:1)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:406)
at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374)
at org.springframework.orm.hibernate3.HibernateTemplate.find(HibernateTemplate.java:912)
at com.myOrg.myProject.asset.AssetDAO.exampleList(AssetDAO.java:142)
at com.myOrg.myProject.navigator.NavigatorController.assetGrid(NavigatorController.java:163)
Again, this works just fine when there are separate parameters, but when they are placed together this happens. The same error can be recreated using unnamed parameters only the "unexpected token" is the second "?" in the query string. How do I put two parameters, named or unnamed, next to each other as would make sense in an ORDER BY statement.
Thanks,
-Cliff
You are using find, not
findByNamedParams
See here. For the Spring 3 API, see here.
Also note that the HibernateTemplate documentation says
NOTE: As of Hibernate 3.0.1,
transactional Hibernate access code
can also be coded in plain Hibernate
style. Hence, for newly started
projects, consider adopting the
standard Hibernate3 style of coding
data access objects instead, based on
SessionFactory.getCurrentSession().
You cannot use parameters (named or positional) in the ORDER BY clause. You can only use them in the WHERE clause.
Why do you need to parameterize these anyway? As long as the values for orderBy and orderDirection are not coming from user input, you can safely just concatenate the values into the query.
if orderDirection == Sort.ASC) {
queryString += " ASC";
}
else {
queryString += " DESC";
}
etc
Params are for specifying values not for builing up sql syntax. Just concat the strings.

Categories

Resources