Generating predicate for latest date value - spring

I need to create a predicate to fetch data from a table where regId = ? (||) or (&&) estCode = ? && latest (referralEntryDate)
fetch the data for latest date
#Override
public Predicate toPredicate(Root<ReviewMedicalStatus> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
List<Predicate> predicatesReg = new ArrayList<Predicate>();
if (revStatusDto.getRegId() != null && !StringUtils.isEmpty(revStatusDto.getRegId())) {
predicatesReg.add(cb.equal(root.get("regId"), revStatusDto.getRegId()));
}
if (revStatusDto.getEstCode() != null && !StringUtils.isEmpty(revStatusDto.getEstCode())) {
predicatesReg.add(cb.equal(root.get("estCode"), revStatusDto.getEstCode()));
}
Expression maxExpression = cb.max(root.get("referralEntryDate"));
predicatesReg.add(maxExpression);
//predicatesReg.add(cb.max(root.get("referralEntryDate")));
return cb.and(predicatesReg.toArray(new Predicate[predicatesReg.size()]));
}
This is failing as the expression can't be passed as a parameter to predicate. How can I get the data for latest referralEntryDate?

Instead of max you have to use greatest for dates. Max is for Numeric types. In order to put it in a predicate you need to make a subquery out of it. Reference: JPA Criteria select all instances with max values in their groups. This isn't exactly your set of entities, but it should give you the idea:
CriteriaBuilder cb = em.getCriteriaBuilder();
// make main query for Content
CriteriaQuery<Content> q = cb.createQuery(Content.class);
Root<Content> c = q.from(Content.class);
// make subquery for date
Subquery<Date> sq = q.subquery(Date.class);
Root<Content> c2 = sq.from(Content.class);
// get the max date in the subquery
sq.select(cb.greatest(c2.<Date>get("date")));
// make a predicate out of the subquery
Predicate p = cb.equal(c.get("date"), sq);
// assign predicate to the main query
q.where(p);
// and get the results
Content r = em.createQuery(q).getSingleResult();
System.out.println(r);

Related

Generic criteriaUpdate set boolean = !boolean

I want to use criteriaUpdate to create an update query like this:
UPDATE <SOME TABLE>
SET SELECTED = !SELECTED
WHERE
[DYNAMIC QUERY HERE]
The closest I could get was with the code:
public <T> Query createRevertSelectionQuery(Class<T> clazz, EntityManager em, Specification<T> s) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaUpdate<T> criteriaUpdate = cb.createCriteriaUpdate(clazz);
Root<T> root = criteriaUpdate.from(clazz);
Predicate p = cb.and(new Predicate[] {s.toPredicate(root, null, cb)});
Expression<Boolean> e =cb.not((root.get("selected").as(Boolean.class)));
Path<Boolean> selected = root.get("selected");
criteriaUpdate.set(selected, e);
criteriaUpdate.where(p);
Query q = em.createQuery(criteriaUpdate);
return q;
}
but it fails because I get the following query:
update com.redknee.suspense.mgt.model.Moc as generatedAlias0
set generatedAlias0.selected = generatedAlias0.selected <> true
where
[dynamic query]
giving me the error
org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: <> near line 1, column 118
Anyone can help please?
I am not sure if this is a bug or if it is just not meant to be used this way .
In where-clause NOT and any other operands work like a charm. But, no matter what you try Hibernate query builder seems always to optimize those parenthesis away (in my opinion it might still be a good habit to always use parenthesis but its only an opinion).
One way to force parenthesis is to use JPA Subquery. See below example. Note that i have slightly altered the JPA object names by my own taste and not included the Specification because it is not relevant to this solution:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaUpdate<T> update = cb.createCriteriaUpdate(clazz);
Root<T> from = update.from(clazz);
Path<Boolean> selected = from.get("selected");
// Subquery just "joins back" to the same row and
// returns a negated boolean value of "selected" from the original row
Subquery<Boolean> subSelect = update.subquery(Boolean.class);
Root<T> subFrom = subSelect.from(clazz);
subSelect.select(cb.not(selected));
subSelect.where(cb.equal(from.get("id"), subFrom.get("id")));
update.set(selected, subSelect);

Building LINQ Expression Getting Ignored

I'm trying to build a linq query coming from a table grid from the client side, so im expecting page offset, page start, order and the traditional paging parameters. I have the following code:
[Route("api/settings/logs")]
public Rest.DatatablesResponse GetLogs(int draw, int start, int length) {
var query_string = Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value);
var search = query_string["search.value"];
int order_column = int.Parse(query_string["order[0].column"]);
var order_direction = query_string["order[0].dir"];
var count = db.Logs.Count(q => q.Mode == 2);
var logs = (from l in db.Logs
where l.Mode == 2
select new {
id = l.ID,
mode = l.Mode,
phase_id = l.Phase.ID,
created = l.Created,
user = l.User.Name,
blender_name = l.Blender.Name,
oil_name = l.Oil,
oil_quantity = l.OilQuantity,
production_cycle_name = l.ProductionCycle.Name
});
if (order_direction == "asc") {
if (order_column == 0) logs.OrderBy(q => q.created);
else if (order_column == 2) logs.OrderBy(q => q.production_cycle_name);
} else {
if (order_column == 0) logs.OrderByDescending(q => q.created);
else if (order_column == 2) logs.OrderByDescending(q => q.production_cycle_name);
};
if (!string.IsNullOrEmpty(search)) {
logs.Where(q => q.blender_name.Contains(search) ||
q.oil_name.Contains(search) ||
SqlFunctions.StringConvert((decimal)q.id).Contains(search));
}
logs.Skip(start).Take(length);
DateTime dtDateTime = new DateTime(1970,1,1,0,0,0,0,System.DateTimeKind.Utc);
var steps = from l in logs.ToList()
select new {
id = l.id,
message = StringHelpers.FormatWith(_tpl_message[l.phase_id.ToString() + l.mode.ToString() ], l) ,
created = dtDateTime.AddSeconds(l.created).ToString("h:mmtt - MMMM d, yyyy"),
production_cycle_name = l.production_cycle_name
};
return new Rest.DatatablesResponse {
draw = draw,
recordsTotal = count,
recordsFiltered = count,
data = steps.ToArray()
};
}
My problem is the skip and take and orderby expressions are getting ignored for some reason, and this is the SQL code generated just before converting my linq expressions to a list. From my understanding, the query should not be executed or evaluated until my logs.ToList() call, so the ordering and take/skip should be taken into account, but it's not:
{SELECT
[Extent1].[ID] AS [ID],
[Extent1].[Mode] AS [Mode],
[Extent1].[Phase_ID] AS [Phase_ID],
[Extent1].[Created] AS [Created],
[Extent2].[Name] AS [Name],
[Extent3].[Name] AS [Name1],
[Extent1].[Oil] AS [Oil],
[Extent1].[OilQuantity] AS [OilQuantity],
[Extent4].[Name] AS [Name2]
FROM [dbo].[Steps] AS [Extent1]
LEFT OUTER JOIN [dbo].[Users] AS [Extent2] ON [Extent1].[User_Id] = [Extent2].[Id]
LEFT OUTER JOIN [dbo].[Blenders] AS [Extent3] ON [Extent1].[Blender_ID] = [Extent3].[ID]
LEFT OUTER JOIN [dbo].[ProductionCycles] AS [Extent4] ON [Extent1].[ProductionCycle_ID] = [Extent4].[ID]
WHERE 2 = [Extent1].[Mode]}
Irrelevant P.S. I'm using the not so clever ifs for building the order expression instead of using DynamicLINQ since i have only two sortable columns.
logs.Skip(start).Take(length);
Creates a IQueryable<T> where T is the same anonymous type of which logs is an IQueryable<T> but with start items skipped. Then from that it creates a similarly typed IQueryable<T> where lenght items are the most that will be taken.
Then it throws that away and lets it be garbage collected. (Or ideally the compiler or jitter steps will realise it's thrown away and cut out the whole thing).
Then logs.ToList() goes back to the logs you still have and creates a list from it.
You should replace the Skip and Take line with:
logs = logs.Skip(start).Take(length);
So that you are actually making use of this skipping and taking.
I'm using the not so clever ifs for building the order expression instead of using DynamicLINQ since i have only two sortable columns.
There's nothing particularly not-clever about that, except that you make the same mistake; apply the OrderBy and then throwing away the result instead of using it. Likewise with the Where. You need logs = logs.OrderBy(...) etc.
I'd also question from l in logs.ToList() select new {…} here.
It might be the best approach, if obtaining that list in one step has some advantage. However otherwise:
from l in logs select new {…}
Do the select work on the database, retrieving just what you need.
from l in logs.AsEnumerable() select new {…}
Do the select work in the application, appropriate if part of it cannot be converted to database work, but do it as it comes rather than loading it all into memory first.
from l in await logs.ToListAsync() select new {…}
Has the downside of ToList() but in asynchronous uses, then (assuming your provider has a ToListAsync() method) allows for awaiting.
ToList() is rarely the best option here.

Selecting first items in GroupBy when using custom Class

I have a very basic sql view which joins 3 tables: users, pictures, and tags.
How would one create the query below in a way that it won't list the same pictures more than once? In other words, I want to Group By pictures (I think) and return get the first insance of each.
I think this is very similar to the post Linq Query Group By and Selecting First Items, but I cannot figure out how to apply it in this case where the query is instantiating MyImageClass.
validPicSummaries = (from x in db.PicsTagsUsers
where x.enabled == 1
select new MyImageClass {
PicName = x.picname,
Username= x.Username,
Tag = x.tag }).Take(50);
To exclude duplicates, you can use the Distinct LINQ method:
validPicSummaries =
(from x in db.PicsTagsUsers
where x.tag == searchterm && x.enabled == 1
select new MyImageClass
{
PicName = x.picname,
Username= x.Username,
Tag = x.tag
})
.Distinct()
.Take(50);
You will need to make sure that the objects are comparable so that two MyImageClass objects that have the same PicName, Username, and Tag are considered equal (or however you wish to consider two of them as being equal).
You can write a small class that implements IEqualityComparer<T> if you would like to have a custom comparer for just this case. Ex:
private class MyImageClassComparer : IEqualityComparer<MyImageClass>
{
public bool Equals(MyImageClass pMyImage1, MyImageClass pMyImage2)
{
// some test of the two objects to determine
// whether they should be considered equal
return pMyImage1.PicName == pMyImage2.PicName
&& pMyImage1.Username == pMyImage2.Username
&& pMyImage1.Tag == pMyImage2.Tag;
}
public int GetHashCode(MyImageClass pMyImageClass)
{
// the GetHashCode function seems to be what is used by LINQ
// to determine equality. from examples, it seems the way
// to combine hashcodes is to XOR them:
return pMyImageClass.PicName.GetHashCode()
^ pMyImageClass.UserName.GetHashCode()
^ pMyImageClass.Tag.GetHashCode();
}
}
Then when you call distinct:
...
.Distinct(new MyImageClassComparer())
.Take(50);

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Linq.IQueryable'

I want to define a function containing a Linq query as bellow:
public IQueryable GetBasket(Guid userId)
{
DabbaghanDataContext db = new DabbaghanDataContext();
int rowNo = 0;
var query = (from c in db.Carts
join co in db.CartOrders on c.Id equals co.Cart_Id
join p in db.Products on co.Product_Id equals p.Id
where c.UserId == userId && c.Issued == false
select new
{
co.Quantity,
co.TotalPrice,
p.Code,
p.Price,
p.Thumbnail
}).AsEnumerable().Select(r => new
{
RowNumber = ++rowNo,
Quantity = r.Quantity,
TotalPrice = r.TotalPrice,
Code = r.Code,
Price = r.Price,
Thumbnail = r.Thumbnail
});
return query;
}
I get error
Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Linq.IQueryable'.
on the return query line.
What is the problem? How can I solve this problem? Please help.
Your problem is the call to AsEnumerable- It converts the IQueryable to a IEnumerable; and therefore, you cannot return it as an IQueryable.
Correct me if I am wrong, but the second select seems to only add the row number to the result. You might as well want to do that together with the initial select, and skip the call to AsEnumerable().
Possible solutions: Rewrite the query to not use AsEnumerable (if you want an IQueryable returned), or you could change the return type to be IEnumerable, if that is a better fit for your problem.
In return query; change that to return query.AsQueryable();
And also try to change the method signature to use IQueryable instead of the nongeneric one

How can I get my orderby to work using an anonymous type?

What do I put in my order by?? I want to order by Name. I have moved the orderby after the distinct because I read that it needs to be done last.
var result = (from r in db.RecordDocs
where r.RecordID == recordID
select new
{
DocTypeID = r.Document.DocType.DocTypeID,
Name = r.Document.DocType.Name,
Number = r.Document.DocType.Number
}
).Distinct().OrderBy( );
Just do
.OrderBy(doc => doc.Name)
Another option, if you really prefer the query expression syntax would be to chain your query construction across multiple statements:
var query = from r in db.RecordDocs
where r.RecordID == recordID
select new
{
DocTypeID = r.Document.DocType.DocTypeID,
Name = r.Document.DocType.Name,
Number = r.Document.DocType.Number
};
query = query.Disctinct();
query = from doc in query orderby doc.Name select doc;
Since all of these methods are deferred, this will result in the exact same execution performance.

Resources