How to convert my query to Criteria in grails - grails

class FaciltyUserRole{
User user
Role permission
Facility facility
}
class Facility{
String id
String groupName
}
These are my domains. I would like to make a query and fetch the facilities with a given user, permission, and the groupName. How can I do that? I have already started my criteria with this, I just have no idea how to filter the facilities I get based on the groupName.
def query = {
and{
eq("user", user)
eq("role", permission)
}
projections {
property("facility")
}
}
def facList = FacilityUserRole.createCriteria().list(query)

if my understanding is correct this is what you are looking for
def query = {
and{
eq("user", user)
eq("role", permission)
facility{
eg("groupName", groupName)
}
}
}

Related

Grails Criteria - list contents

These are my domain objects
User{
hasMany = {roles: UserRole}
}
UserRole{
User user
Role role
}
Role{
String authority
}
I need to find users based on their Role. For that I am trying to use the following criteria:
def role_admin = Role.findByAuthority('ROLE_ADMIN')
def criteria = new DetachedCriteria(User).build {
roles{
role{
idEq(role_admin.id)
}
}
}
result.users = criteria.list(params)
result.total = criteria.count()
The above will always return one result, even though I have verified by looking at the database directly that there should be more results. The params passed to list are correct, but I tried removing them just to be sure. I can't see what is wrong with the above, any suggestions ?
I also tried this
roles{
role{
eq("authority","ROLE_ADMIN")
}
}
But it is throwing exception:
Unknown column 'role_alias2_.authority' in 'where clause'
this works for me:
def criteriaUsers = UserRole.createCriteria()
def users = criteriaUsers.listDistinct{
eq("role", role_admin)
}.user
Side note: from the nomenclature of your classes it looks like you are using spring-security-core plugin. In my humble opinion the hasMany = [roles: UserRole] is redundant as the association User - Role is already being modeled in the UserRole class.

Spring Data Neo4j : find all nodes with a list of propertyvalues

I have a neo4j social network db and have a usecase to look through a bunch of user ids and check how many user ids are present in the graph. The User looks like this :
#NodeEntity
public class User {
#GraphId
Long nodeId;
#Indexed(indexName = "uid",unique = true)
Long uid;
}
my check would look somrthing like this :
for(Long uid : allUserIds){
User friend = userRepo.findByPropertyValue("uid", uid);
if(friend!=null){
//Create a relationship
}else{
//continue
}
}
Is there a way I can get rid of the findByPropertyValue for every single userId ? Is there a faster way thru which I can get all existing Users given a bunch of uids in one request ?
Thanks..
You could try with a Cypher query:
Map<String, Object> params = new HashMap<String, Object>();
String query = "start user=node:__types__(className=\"<package>.User\") where ID(user)>=0 and ID(user) in {uids} return user"; // substitute <package> with the full package name
params.put("uids", allUserIds); // allUserIds should be a Collection<Long>
Collection<User> users = neo4jOperations.query(query.toString(), params).to(User.class).as(Collection.class);
for (User user: users) {
...
}
You're already doing it right.
There is also findByQuery afaik, that allows you to pass in a lucene query which would be "uid: value1 value2 value3"

Defining OR Condition with grails criteria api

I have the following domain objects:
class User {
String name
Transaction transaction
static constraints = {
transaction nullable: true
}
}
class Transaction {
boolean successful
User user
static belongsTo = User
}
I want to select all users that have no successful transaction. This means I want the users without any transaction (transaction == null) and the users that have a transaction with the successful value false (transaction.successful == false). I want to do this with the Criteria API (because this can be combined with other conditions based on user input).
I tried this:
def c = User.createCriteria()
def results = c {
or {
isNull 'transaction'
transaction {
eq 'successful', false
}
}
}
However this gives me only the users that have a transaction (with the successful value false). But I do not get the users where transaction is null
The following code shows how I created some sample data:
def createUserAndTransaction(String name, Boolean successful = null) {
User u = new User(name: name)
if (successful != null) {
Transaction t = new Transaction(user: u, successful: successful)
u.setTransaction(t)
}
u.save()
}
def init = { servletContext ->
createUserAndTransaction 'john', true
createUserAndTransaction 'mike', false
createUserAndTransaction 'pablo'
}
My criteria query only returns mike in this case. But I want mike and pablo. What am I missing?
So the problem is that it defaults to an inner join. You have to create an alias for the table and define its join type:
createAlias("transaction", "t", CriteriaSpecification.LEFT_JOIN)
or {
isNull("t")
eq("t.successful", false)
}

Grails/GORM simple many-to-many join query not working?

OK, I'm new to Grails, as well as Hibernate. I'm prototying something simple, and am stuck on querying the simplest many-to-many relationship via a join.
My model objects are:
class User {
static hasMany = [roles:Role]
String firstName
String lastName
String username
String password
// ... constraints and hooks omitted ...
}
class Role {
static hasMany = [users:User]
static belongsTo = User
String name;
// ... constraints and hooks omitted ...
}
After loading some data, I can see:
groovy:000> User.list().each { user-> println "$user.username : ${user.roles.collect {it.name}}"}
smendola : [Admin, Reviewer]
jripper : []
jbauer : []
groovy:000> Role.list().each { role-> println "$role.name: ${role.users?.collect {it.username}}"}
Admin: [smendola]
Guest: null
Reviewer: [smendola]
So, user smendola has two roles; other users have no roles; and the relationship is working from both directions. Good.
Now the question:
I want to query for user with some role. Of course I could use the return value from either of the above two queries and search it in Groovy, but I want the db to do this work.
I have futzed for HOURS trying to to construct a query that will give me the desired result, to no avail. I believe I have followed online examples to a tee, and yet I cannot get this query to work.
One version of the query I've tried:
groovy:000> User.where { roles.name == 'Admin' }.list()
===> []
Or this variant:
groovy:000> User.where { roles {name == 'Admin'}}.list()
===> []
I've tried many, many other variations, including using .id, or role=someRoleInstance, etc. Nothing works. I'm out of ideas. Any help out there?
The database is h2, by the way.
Grails version 2.0.0
Thanks!
ADDED:
Two variants that were suggested, but also did not work:
groovy:000> User.createCriteria().list{ roles { eq('name', 'Admin') } }
===> []
groovy:000>
groovy:000> roleName = 'Admin'
===> Admin
groovy:000> def users = User.withCriteria {
groovy:001> roles {
groovy:002> eq('name', roleName)
groovy:003> }
groovy:004> }
===> []
groovy:000>
User.createCriteria().list{
roles{
eq('name', 'Admin')
}
}
Try using criteria
This should work if you're willing to use a criteria query instead:
String roleName = 'Admin'
def users = User.withCriteria {
roles {
eq('name', roleName)
}
}

Filtering filtered data

I'm new to grails and MVC so please bear with me.
I have some links on my GSP that do some static filtering. For instance, the example below returns only
those Request domain class instances with status Open. But I also want to be able to do some dynamic filtering on the same model (results in the code bellow).
Use case would be something like this: User sees all Request domain class instances in the table. He clicks on the link Open requests and gets only those Request instances that have status property with value Open. Than he sets dateFrom and dateTo using date picker control and clicks on the Filter button which calls the method/action that further filters data from the table. So it should return only those request that are opened and that are created within the specified period.
def openedRequests = {
def contact = Contact?.findByUser(springSecurityService.currentUser)
def productlines = contact.productlines()
def requestCriteria = Request.createCriteria()
def results = requestCriteria.list {
eq("status", "Open")
and {
'in'("productline",productlines)
}
}
render(view:'supportList', model:[requestInstanceList:results, requestInstanceTotal: results.totalCount])
}
EDIT
On my GSP I have few links that call controller actions which perform some domain class instances filtering. For example I have OpenedRequests, ClosedRequests, NewRequests. But I also have some textboxes, comboboxes, datePicker controls for additional filtering. I call the filterRequests action with a button.
def filterRequests = {
def contact = Contact?.findByUser(springSecurityService.currentUser)
def productlines = contact.productlines()
def requestCriteria = Request.createCriteria()
def results = requestCriteria.list {
if(params.fDateFrom && params.fDateTo){
def dateFrom = new SimpleDateFormat("dd.MM.yyyy").parse(params.fDateFrom_value)
def dateTo = new SimpleDateFormat("dd.MM.yyyy").parse(params.fDateTo_value)
between("dateCreated",dateFrom,dateTo)
}
if(params?.fStatus){
eq("status",params.fStatus)
}
if(params?.fCompany){
eq("company", params.fCompany)
}
and {'in'("productline",productlines)
}
if(params.sort != null && params.order != null){
order(params.sort, params.order)
}
}
render(view:'supportList', model:[requestInstanceList:results, requestInstanceTotal: results.totalCount])
}
I want to be able to filter Request instances with some of mentioned links and than if I set up some additional filters, for example dateFrom i dateTo with datePicker. I want those filters to be aware of previous filtering with link if there were any. What is the right way to do this?
You can use DetachedCriterias which where introduced with Grails 2.0.
A DetachedCriteria is independed from any session and can be reused easily:
def openRequests = new DetachedCriteria(Request).build {
eq("status", "Open")
and {
'in'("productline",productlines)
}
}
Then upon your next sub-filter request you can reuse the DetachedCriteria and perform a sub-query on it, like:
def results = openRequests.findByStartDateBetweenAndEndDateBetween(dateFrom, dateTo, dateFrom, dateTo)
Of course you have to remember somehow what the original query was (session, request param), to use the correct criteria as a basis for the sub-query.
(Disclaimer: I haven't yet tried detached criterias myself)
David suggested that I use Detached Criteria but I am using Grails 1.3.7 for my app. So, at the moment this isn't an option. I also thought of using database views and stored procedures but I wasn't sure how that will work with Grails (but that is something that I will definitely have to explore) and I wanted some results fast so I did something not very DRY. When I filter table with one of the mentioned links I save the name of the link/action in session and in filterRequest action (that does additional filtering) I check the session to see if there has been any previous 'link filtering' and if it were I apply those filters on the table with criteria, and after that I apply the filters that were manualy entered. I don't like it but that's all I came up with with my limited understanding of Grails. Below is my filterRequest action:
def filterRequests = {
def contact = Contact?.findByUser(springSecurityService.currentUser)
def productlines = contact.productlines()
def requestCriteria = Request.createCriteria()
def results = requestCriteria.list {
if(session.filter == "newRequests"){
and{
isNull("acceptedBy")
ne("status", "Closed")
}
}
if(session.filter == "openRequests"){
and{
ne("status",'Closed')
}
}
if(session.filter == "closedRequests"){
and{
eq("status", "Closed")
}
}
if(session.filter == "myRequests"){
and{
eq("acceptedBy", contact.realname)
}
}
if(params.fDateFrom && params.fDateTo){
def dateFrom = new SimpleDateFormat("dd.MM.yyyy").parse(params.fDateFrom_value)
def dateTo = new SimpleDateFormat("dd.MM.yyyy").parse(params.fDateTo_value)
and{
between("dateCreated",dateFrom,dateTo)
}
}
if(params?.fAcceptedBy){
and{
eq("acceptedBy", params.fAcceptedBy)
}
}
if(params?.fStartedBy){
and{
eq("startedBy", params.fStartedBy)
}
}
if(params?.fCompany){
and{
ilike("company", "%" + params.fCompany +"%")
}
}
and {'in'("productline",productlines)
}
if(params.sort != null && params.order != null){
order(params.sort, params.order)
}
}
}

Resources