findAllWhere and List fetch - grails

So I have the domain class as follows:
class Enrollment {
Course course
Date date
User user
static constraints = {
}
}
In my controller, I have this action :
def persons = Enrollment.list(fetch :[user : "a"])
render persons
I am trying to fetch only a user named "a" and its corresponding map. But it displays all..I tried FindAllWhere but throws an error
No such property: user for class: tester.EnrollmentController

I am assuming that the User class has a name property.
What about:
def user = User.findByName("a")
def persons = user ? Enrollment.findAllByUser(user) : []
Assuming here that you can find a unique user (name probably isn't unique enough), otherwise I would do something like:
def persons = Enrollment.createCriteria().list{
user {
eq('name', "a")
}
}

Related

grails - org.hibernate.QueryException (could not resolve property)

I'm trying to get the list of a specific rental from the current user.
Code in controller:
def index() {
if (isLoggedIn()) {
String username = getPrincipal().username
def accountInstance = Account.findByUsername(username)
def rentalInstanceList = Rental.findAll("from Rental as r where r.account_id=:accountid", [accountid: accountInstance.id])
}
}
account_id is a foreign key.
After running I get the error:
could not resolve property: account_id of: ers.Rental
What am I doing wrong?
Generally, in HQL you have to use the field names as defined in your domain classes. So, your query should look like:
def list = Rental.findAll("from Rental where accountId=:accountid", [accountid: accountInstance.id])
or
def list = Rental.findAllByAccount accountInstance
or even
def list = Rental.findAllByAccount getPrincipal()
if the return type of getPrincipal() has the id field.
findAll is not limited to instances of the calling class so I use executeQuery instead. https://stackoverflow.com/a/8916483/5011228

How to compare collection item using createCriteria?

Registration domain has a collection of discounts.
static hasMany = [ discounts: Discount]
I want to extract all Registrations that have a particular discount applied.
In the following code i want to get all registrations whose collection has the discount of id disid. How can i achieve that? I appreciate any help!
def disid = Discount.get(1).id
def regs = Registration.createCriteria().list(){
eq('compositeEvent', cod.compositeEvent)
}
Try this:
def disid = Discount.get(1).id
def regs = Registration.withCriteria() {
discounts {
eq 'id', disid
}
}
See http://emmanuelrosa.com/articles/gorm-for-sqladdicts-where-clause/

Grails GORM : SELECT AS

I'm trying to get all the Users that are born today with GORM but I'm failing to write this query in Grails:
SELECT
DAY(dateOfBirth) AS 'day',
MONTH(dateOfBirth) AS 'month'
FROM Users
WHERE day = '...' AND month = '...';
... will be replaced with today's values.
Minimal User Domain class
class User {
Date dateOfBirth
...
}
Minimal UserService class
#Transactional
class UserService {
def getTodayBirthdays() {
def bornTodayQuery = User.where{
/* I'm thinking here I must
* select the DAY and MONTH from the DB
* and compare it with the today ones.
*/
}
User usersBornToday = bornTodayQuery.findAll()
usersBornToday
}
}
Any ideas how can I do an alias (SELECT field AS alias) with GORM?
I'm using:
Grails 2.4.4
Thanks!
You could use a where query in your service:
#Transactional(readOnly = true)
def listBirthday(int _month, int _day) {
// Calendar.JANUARY equals to zero!
def m = _month + 1
// Run a where query on the users
User.where {
month(dateOfBirth) == m && day(dateOfBirth) == _day
}
}
#Transactional(readOnly = true)
def listBirthdayToday() {
def cal = Calendar.getInstance()
listBirthday(cal.get(cal.MONTH), cal.get(cal.DAY_OF_MONTH))
}
In addition to month and day there are some other functions, here is the documentation (look for "Other Functions")
Any ideas how can I do an alias (SELECT field AS alias) with GORM?
(SELECT field AS _alias)
Putting an underscore (_) as prefix to alias worked for me with grails-2.5.6
I have not found it in documentation but using trail and error method.

How can I get a set of field values in groovy?

class Book {
String title
}
def book = new Book(title: 'title1')
def book = new Book(title: 'title2')
def book = new Book(title: 'title3')
How can I get the set of titles? Something like titleSet = ['title1', 'title2', 'title3']
I thought maybe something like def titleSet = Book.findTitles(); would work but I can't find anything like that.
I know I could do:
def books = Book.list()
def titleSet
for(def book : books)
titleSet.add(book.title)
But I'm looking for a groovier way.
This goes through all the books for their title and creates a Set instead of a List.
Book.all.title as Set
UPDATE
The above will fetch all Book instances which might be heavy if you only need title. You can also try using criteria or HQL to get only list of titles.
def titleSet = Book.createCriteria().listDistinct {
projections {
property('title')
}
}
Try
Set titleSet = books*.title
Or
Set titleSet = books.collect { it.title }

Grails accessing nested fields using gstrings

I am trying to access a nested field using gstring but it throws exception groovy.lang.MissingPropertyException
I have two classes
Class Person{
Address address
}
Class Address{
String city
}
Somewhere in my code I am doing,
def person = Person.get(1)
def field = "address.city"
def city = person."${field}"
The line where I am trying to fetch city from person is throwing groovy.lang.MissingPropertyException
If I try to fetch a direct property using gstring it works but the above given code doesnt work.
Any help?
What you're doing here is trying to access a property by name address.city which is equal to person."address.city", which means that the dot here gets considered as part of property name - not as access separator as you expect. The following code should resolve your property:
def city = field.tokenize('.').inject(person) {v, k -> v."$k"}
I think that the problem is with dot operator for access to a subproperty.
This works:
class Person{
String address
}
def person = new Person(address:'Madrid')
def field = 'address'
assert 'Madrid' == person."${field}"
This works:
class Person{
Address address
}
class Address {
String city
}
def person = new Person(address: new Address(city: 'Madrid'))
def field = 'address'
def subField = 'city'
assert 'Madrid' == person."${field}"."${subField}"

Resources