Spring Data Neo4j 4 and Pageable vs repository method ORDER BY parameters - cypher

#Query("MATCH (parentD:Decision)-[:CONTAINS]->(childD:Decision)-[ru:CREATED_BY]->(u:User) WHERE id(parentD) = {parentDecisionId} RETURN childD, ru, u ORDER BY childD.createDate DESC")
List<Decision> getChildDecisions(#Param("parentDecisionId") Long parentDecisionId);
Is it possible to pass order expression like childD.createDate and order direction like ASC or DESC via Spring Data Neo4j 4 repository method parameters ? If so, could you please show an example.
Or do I need to use Pageable in this case ?

Related

nhibernate querying over other query results

Hello i'm trying to get all users which have had payments at least 6 months over the given period (which must be a year). I've written SQL which works fine, but i have difficulties trying to convert it to nhibernate.
SQL:
SELECT COUNT(UserId) AS paidMonthsCount, UserId FROM (
SELECT DISTINCT UserId,
YEAR(PayDate) as _year,
MONTH(PayDate) as _month
FROM Payments
WHERE PayDate >= '2014-04-02T00:00:00' AND PayDate < '2015-04-02T23:59:00'
)result GROUP BY result.UserId
i have converted inner SQL:
var subQuery = Session.QueryOver(() => paymentAlias)
.SelectList(list => list
.Select(Projections.Distinct(Projections.Property<VelferdPayment>(p => p.Client.Id)).WithAlias(() => userWithHelp.Id))
.Select(p => p.AssignmentYear).WithAlias(() => userWithHelp.AssignmentDate)
)
.WhereRestrictionOn(p => p.AssignmentDate)
.IsBetween(parameters.FromDate)
.And(parameters.ToDate);
which selects the distinct part and i have the other part which is selecting from result:
var query = Session.QueryOver(() => userWithHelp).
SelectList(list => list
.SelectCount(p=> p.Id).WithAlias(()=> userWithHelpCount.Count)
.SelectGroup(p => p.Id).WithAlias(() => userWithHelpCount.Id)
)
.TransformUsing(Transformers.AliasToBean<UserWithHelpCount>())
.List<UserWithHelpCount>();
How can i queryover the subQuery results or is it possible to write single request to SQL. Working for a long time please help.
In general, with NHibernate we can only (or mainly) query Entities, not TABLES. Other words, we firstly map tables or views or even some <subselect>s into entities. The below mapping of the User (C# object User)
<class name="user" table="[dbo].[user_table]" ...
Will allow us to create query over C# User.
session.QueryOver<User>()...
Behind the scene it will generate FROM clause, which will contain the content of table attribute, i.e. FROM [dbo].[user_table]
That's it. There is no other way how to set the generated FROM clause. Just by mapping.
But there is a way which allow us to use existing ADO.NET connection to create custom query and even convert its result to some entity, or DTO. It is CreateSQLQuery() API:
17.1.5. Returning non-managed entities
It is possible to apply an IResultTransformer to native sql queries. Allowing it to e.g. return non-managed entities.
sess.CreateSQLQuery("SELECT NAME, BIRTHDATE FROM CATS")
.SetResultTransformer(Transformers.AliasToBean(typeof(CatDTO)))
This query specified:
the SQL query string
a result transformer
The above query will return a list of CatDTO which has been instantiated and injected the values of NAME and BIRTHNAME into its corresponding properties or fields.
So, we can use native SQL SELECT statements to get any results. We can even create some custom DTO and let NHibernate to transform result into them...

Django Queries: related subquery

I have 3 Models: Offer, Request and Assignment. Assignment makes a connection between Request and Offer. Now I want to do this:
select *
from offer as a
where places > (
select count(*)
from assignment
where offer_id = a.id and
to_date > "2014-07-07");
I am not quiet sure how to achieve this with a django QuerySet... Any tips?
Edit: The query above is just an example, how the query in general should look like. The django model looks like this:
class Offer(models.Model):
...
places = models.IntegerField()
...
class Request(models.Model):
...
class Assignment(models.Model):
from_date = models.DateField()
to_data = models.DateField()
request = models.ForeignKey("Request",related_name="assignments")
offer = models.ForeignKey("Offer",related_name="assignments")
People now can create a offer with a given amount of places or a request. The admin then will connect a request with an offer for a given time. This is saved as an assignment. The query above should give me a list of offers, which have still places left. Therefore I want to count the number of valid assignments for a given offer to compare it with its number of places. This list should be used to find a possible offer for a given request to create a new assignment.
I hope this describes the problem better.
Unfortunately related subqueries aren't directly supported by ORM operations. Usage of .extra(where=...) should be possible in this case.
To get the same results without using a subquery something like the following should work:
Offer.objects.filter(
assignment__to_date__gt=thedate
).annotate(
assignment_cnt=Count('assignment')
).filter(
assignment_cnt__lte=F('places')
)
The exact query depends on the model definitions.
query = '''select *
from yourapp_offer as a
where places > (
select count(*)
from yourapp_assignment
where offer_id = a.id and
to_date > "2014-07-07");'''
offers = Offer.objects.raw(query):
https://docs.djangoproject.com/en/1.6/topics/db/sql/

How can I use IF(bool, a, b) clause in CakePHP's order parameter?

I'm writing a SQL query to order products by price asc, but putting products with 0 price at last.
As I know, I can use ORDER BY IF(price=0,1,0) ASC, price ASC to get it done. But when I pass 'order' => array('IF(Product.price=0, 1, 0) ASC', 'Product.price' => 'ASC') to the paginate component in CakePHP, the IF part is dismissed automatically.
I'm wondering how to get it done in CakePHP with CakePHP style param array?
i think you want this...
if($condition) ? /**want do you want if true/ : /** do what you want if false/;
hope it help

Linq to Nhibernate 3.1 Group By (Or distinct)

I need to do a simple "group by" with a nhibernate query.
My try were :
(from adn in session.Query<Table>()
orderby adn.Data
select adn.Data).Distinct().ToList<string>();
and
session.Query<Table().GroupBy(adn => adn.Data).Select(dat => dat).ToList<string>()
can someone help me to find a solution ?
My goal is to retrieve all the Distinct "Data" Column.
It can be by group by or distinct.
(the 2 solutions would be better for my progression in nhibernate)
Regards
edit
Danyolviax, I tryied your solution
return (from adn in session.Query<Table>()
group adn by adn.Data into dataGroupe
select dataGroupe).ToList<string>();
It doesn't work.
I feared that I use Nhibernate 3.1 (and not 2.1)
Any correction or alternative solution ?
edit 2
In the second solution which works (^^)
I have a list of a class with one property.
In my case, I prefer to have a list of string or int.
Otherwise I should create a specific class for this case.
Do you know a trick.
And thanks for your support.
Look here:
Linq to NHibernate and Group By
here some examples:
http://msdn.microsoft.com/en-us/vcsharp/aa336754
updated
try this with 3.1.0.4000:
var ret = (from adn in session.Query<Table>()
group adn by adn.Data into dataGroup
select new {dataGroup.Key }).ToList();
update
var ret = (from adn in session.Query<Table>()
group adn by adn.Data into dataGroup
select dataGroup.Key).ToList<string>();

NHibernate sorting (SQL as a second option)

I'm using NHibernate as my ORM and I'm trying to sort some data. The data needs to be retrieved paged.
Two of the columns in my Request table are UrgencyID and CreateDate. UrgencyID is a FK to the Urgency table with static data:
1 = Low, 2 = Normal, 3 = High, 4 = Critical.
I need to order my Requests in the following manner.
Critical Requests by CreateDate descending
All other requests by CreateDate descending
So my list of Requests should always have Critical by CreateDate desc at the top and then all other Requests (disregarding UrgencyID) by CreateDate desc
Is it possible to perform this sort order in NHibernate (using the Criteria API)?
If not, how would I do this in SQL? In a stored procedure?
EDIT: Solution thanks to both #DanP and #Michael Pakhantsov
Using the this_ prefix in the sql string as this is the default NHibernate prefix for the primary table selection.
public class OperatorJobQueueOrder : Order
{
public OperatorJobQueueOrder() : base("", true) { }
public override NHibernate.SqlCommand.SqlString ToSqlString(ICriteria criteria, ICriteriaQuery criteriaQuery)
{
return new NHibernate.SqlCommand.SqlString("case this_.JobRequestUrgencyID when 4 then 4 else 0 end desc, this_.CreatedDate");
}
}
You may be able to create a custom sort order to handle this through the critiera api; see this question for an example implementation.
IN SQL ORDER BY will be
ORDER by case UrgencyId when 4 then 4 else 0 end, CreateDate desc