J. Siz
J. Siz

Reputation: 3

Grails: How do I retrieve records by a specific property?

I am creating a basic CRUD application with a Person entity:

class Person {
    public int Age;
    ...
    public int getAge() {
        return this.Age;
    }

    public void setAge(int AgeToSet) {
        this.Age = AgeToSet;
    }
}

I have a controller and I want to retrieve all Persons with an age of 20:

def filter = {
    def c = Person.createCriteria();
    def persons = c.list{
         eqProperty("Age", "20");
     }
    [persons: persons];
}

But this is not working and is, instead, giving me the error:

ERROR StackTrace - Full Stack Trace:
org.hibernate.QueryException: could not resolve property: Age of: project.Person
    at     org.hibernate.persister.entity.AbstractPropertyMapping.propertyException(AbstractPropertyMapping.java:62)

What could be the problem?

Upvotes: 0

Views: 54

Answers (2)

Bryan G Campbell
Bryan G Campbell

Reputation: 271

Since this query is so simple, you may want to just use a DynamicFinder: http://gorm.grails.org/6.0.x/hibernate/manual/index.html#finders

With a Dynamic Finder, you could simplify the query to:

def persons = Person.findAllByAge(20)

Just a suggestion. I use Dynamic Finders as my primary query method. If I need a query that is more complex, I'll resort to a .createCriteria and then a .executeQuery which takes HQL.

Upvotes: 1

rvargas
rvargas

Reputation: 635

Three things:

  • Your Age needs to start with lowercase: age.
  • Your criteria is wrong, you want to use eq. eqProperty compares two properties, but you only need one and a value.
  • Your comparision must be with an int, like this: eq("myage", 20).

Upvotes: 1

Related Questions