JPQL didn't get parameter - jpql

There is my code. Can someone tell me what is wrong?
for(String motorProposalId : proposalMap.keySet()) {
MotorPolicy mp = policyMap.get(motorProposalId);
String query = "SELECT p From Payment Where p.referenceNo = :motorProposalId"+
" AND commenmanceDate >= :startDate AND commenmanceDate <= :endDate";
Query qu = em.createQuery(query);
qu.setParameter("commenmanceDate", mp.getCommenmanceDate());
qu.setParameter("motorProposalId", motorProposalId);
qu.setParameter("startDate", motorDailyCriteria.getStartDate());
qu.setParameter("endDate", motorDailyCriteria.getEndDate());

Query is syntactically incorrect because there is no named parameter commenmanceDate in query string. If commenmanceDate should be named parameter, then it must be prefixed with ':'.
Also then query likely have some semantic problems, because all values included to date comparisons are already known before executing query.

Related

Azure DocumentDB: order by and filter by DateTime

I have the following query:
SELECT * FROM c
WHERE c.DateTime >= "2017-03-20T10:07:17.9894476+01:00" AND c.DateTime <= "2017-03-22T10:07:17.9904464+01:00"
ORDER BY c.DateTime DESC
So as you can see I have a WHERE condition for a property with the type DateTimeand I want to sort my result by the same one.
The query ends with the following error:
Order-by item requires a range index to be defined on the corresponding index path.
I have absolutely no idea what this error message is about :(
Has anybody any idea?
You can also do one thing that don't require indexing explicitly. Azure documentBD is providing indexing on numbers field by default so you can store the date in long format. Because you are already converting date to string, you can also convert date to long an store, then you can implement range query.
I think I found a possible solution, thanks for pointing out the issue with the index.
As stated in the following article https://learn.microsoft.com/en-us/azure/documentdb/documentdb-working-with-dates#indexing-datetimes-for-range-queries I changed the index for the datatype string to RangeIndex, to allow range queries:
DocumentCollection collection = new DocumentCollection { Id = "orders" };
collection.IndexingPolicy = new IndexingPolicy(new RangeIndex(DataType.String) { Precision = -1 });
await client.CreateDocumentCollectionAsync("/dbs/orderdb", collection);
And it seems to work! If there are any undesired side effects I will let you know.

Automapper Project().To Error A query body must end with a select

I'm trying to prevent that a query to an entity bring more columns than necessary. Should only bring those columns specified in the target model.
Below is my code built following some examples to achieve my goal but I get syntax error "A query body must end with a select clause or a group clause linq”
int the query line.
var studentEventsModel = from c in DbContext.StudentEvent.Project().To<StudentEventViewModel>();
Please let me know what I’m doing wrong.
public IEnumerable<StudentEventViewModel> GetStudentEventsListViewModel()
{
Mapper.CreateMap<StudentEvent, StudentEventViewModel>();
var studentEventsModel = from c in DbContext.StudentEvent.Project().To<StudentEventViewModel>();
return studentEventsModel;
}
As #hometoast mentioned you may add select at the end of your query like this:
var studentEventsModel =
from c in DbContext.StudentEvent.Project().To<StudentEventViewModel>() select c;
or alerternatively you may use the lambda expression like this:
var studentEventsModel = DbContext.StudentEvent.Project().To<StudentEventViewModel>();
And as to the question on why you are seeing that error, it is due to the fact that a query syntax must end with select or group, mentioned here in the documentation.
A query expression must begin with a from clause and must end with a
select or group clause. Between the first from clause and the last
select or group clause, it can contain one or more of these optional
clauses: where, orderby, join, let and even additional from clauses.
You can also use the into keyword to enable the result of a join or
group clause to serve as the source for additional query clauses in
the same query expression.

What is wrong in this LINQ Query, getting compile error

I have a list AllIDs:
List<IAddress> AllIDs = new List<IAddress>();
I want to do substring operation on a member field AddressId based on a character "_".
I am using below LINQ query but getting compilation error:
AllIDs= AllIDs.Where(s => s.AddressId.Length >= s.AddressId.IndexOf("_"))
.Select(s => s.AddressId.Substring(s.AddressId.IndexOf("_")))
.ToList();
Error:
Cannot implicitly convert type 'System.Collections.Generic.List<string>' to 'System.Collections.Generic.List<MyCompany.Common.Users.IAddress>'
AllIDs is a list of IAddress but you are selecting a string. The compiler is complaining it cannot convert a List<string> to a List<IAddress>. Did you mean the following instead?
var substrings = AllIDs.Where(...).Select(...).ToList();
If you want to put them back into Address objects (assuming you have an Address class in addition to your IAddress interface), you can do something like this (assuming the constructor for Address is in place):
AllIDs = AllIDs.Where(...).Select(new Address(s.AddressID.Substring(s.AddressID.IndexOf("_")))).ToList();
You should also look at using query syntax for LINQ instead of method syntax, it can clean up and improve the readability of a lot of queries like this. Your original (unmodified) query is roughly equivalent to this:
var substrings = from a in AllIDs
let id = a.AddressId
let idx = id.IndexOf("_")
where id.Length >= idx
select id.Substring(idx);
Though this is really just a style thing, and this compiles to the same thing as the original. One slight difference is that you only have to call String.IndexOf() one per entry, instead of twice per entry. let is your friend.
Maybe this?
var boundable =
from s id in AllIDs
where s.AddressId.Length >= s.AddressId.IndexOf("_")
select new { AddressId = s.AddressId.Substring(s.AddressId.IndexOf("_")) };
boundable = boundable.ToList();

String matching in HQL

I'm creating an HQL query to filter a grid of data:
string formatString = "Type = {0} AND {1} = '{2}' AND CompletedDate > '{3}'
AND CompletedDate < '{4}' AND UserName LIKE '{5}'";
HqlBindingSource.Where = string.Format(formatString, type, keyId, entityID,
fromDate, toDate, toDate, UserTextBox.Text);
The problem I'm having is the string matching on the UserName field. I'm used to working with SQL and I can't get it to match on a value using = or LIKE. Can anyone point me in the right direction for this?
Thanks
I had "toDate" listed twice, so UserTextBox.Text was never used in the query.

JPQL query --- how to use 'is null'

i use the following query in JPQL to query the people whose address column is empty.
List rl =
em.createQuery( "select o from Person as o where
o.address IS NULL" ).setFirstResult(
0).setMaxResults( 50).getResultList();
...
this line of code always return an empty list, obviously the table does has entries that match the condition.
class Person {
Address address;
String name;
... }
class Address {
String name;
... }
anyone knows what's wrong with this jpql statement?
thanks in advance.
As mentioned, address column is empty, then try using IS EMPTY expression instead of IS NULL.
em.createQuery( "SELECT o FROM Person o where (o.address.id IS NULL OR o.address.id = 0").setMaxResults(50).getResultList();
Check constraint according to id's datatype.
Also there is no need to mention setFirstResult(0) as it is not going to skip any results & without it, by default all matching results will be fetched.

Resources