Grails GORM MissingMethodException with 1:N relationship - grails

I have such domain classes:
class ServicesGroup {
Long id
String name
String description
String toString(){
return name
}
static mapping = {
version false
table 'root.services_groups'
id column:'group_id'
name column:'group_name'
description column:'group_desc'
}
}
and
class Step {
Long id
ServicesGroup service
String stepType
Integer stepFrom
Integer stepTo
static constraints = {
stepType(inList:['operator', 'client'])
}
static mapping = {
version false
table 'bill.steps'
service column:'service_group_id'
}
}
The relationship is - one ServicesGroup entry can have multiple Step instances.
However, when in my controller I try to
Step.findByService(3)
I get:
"org.codehaus.groovy.runtime.InvokerInvocationException: groovy.lang.MissingMethodException: No signature of method: Step.findByService() is applicable for argument types: (java.lang.Integer) values: {3}"
However, when I change Step domain class field
ServicesGroup service
to simply
Long service
it works.
What's going on here?

Try it that way:
Step.findByService(ServicesGroup.get(3))

Try
grails clean
grails run-app
Then try again.

Something like Step.findByService([id: 3]) may work. It only cares about the ID anyway for the purposes of the SQL generation. In a lot of cases like this you can toss a fake map into there rather than the real thing, and save yourself some performance.
On the other hand, the abstraction breaks down a bit when you do this.

Related

Grails Criteria Projection - No signature of method projections() is applicable for argument types

As per Grails documentation
Grails also lets you write your domain model in Java or reuse an existing one that already has Hibernate mapping files. Simply place the mapping files into grails-app/conf/hibernate and either put the Java files in src/java or the classes in the project's lib directory if the domain model is packaged as a JAR. You still need the hibernate.cfg.xml though!
So This is exactley what i did.
I have used java domain model and hibernate.cfg.xml file for mapping. I also use
{DomainName}Constraints.groovy for adding Grails constraints. I also used to add functions to {DomainName}Constraints. For example, below is the content of my EmployeeConstraints.groovy
Employee.metaClass.static.findByDepartment = {depCode ->
createCriteria().list {
department{
inList ('code', depCode)
}
}
}
Now this works fine. But, when i add projection to it(code below), just to get the employee code.
Employee.metaClass.static.findByDepartment = {depCode ->
createCriteria().list {
projections { property('empCode', 'empCode') }
department { inList ('code', depCode) }
}
}
I get the below error..
" No signature of method: com.package.script142113.projections() is applicable for argument types.. "
Can someone point me to whats wrong with the code?
Thanks!
The property projection is used to return a subset of an object's properties. For example, to return just the foo and bar properties use:
projections {
property('foo')
property('bar')
}
You're getting an error because you've called the property method with 2 arguments instead of one.
By the way, I see another potential with your code. Grails will automatically create a dynamic finder findByDepartment that has the same name as the method your trying to add via the meta-class. I have no idea which one will take precendence, but I would suggest you avoid this potential problem and simplify your code, by adding this query using Grails' named query support, and call it something like getByDepartment so that the name doesn't class with a dynamic finder.
The answer by Dónal should be the correct one, but I found a strange behavior with grails 3.1. I got the same message using this call:
Announcement.createCriteria().list {
projections {
property('id')
property('title')
}
} .collect { [id: it['id'], title: it['title']] } // it['id'] not found
I fixed it by removing projections closure:
Announcement.createCriteria().list {
property('id')
property('title')
} .collect { [id: it['id'], title: it['title']] } // got the it['id']
Hope this help.

my own id in GORM

I tried to change the standard 'id' in grails:
calls Book {
String id
String title
static mapping {
id generator:'assigned'
}
}
unfortunately, I soon noticed that this breaks my bootstrap. Instead of
new Book (id:'some ISBN', title:'great book').save(flush:true, failOnError:true)
I had to use
def b = new Book(title:'great book')
b.id = 'some ISBN'
b.save(flush:true, failOnError:true)
otherwise I get an 'ids for this class must be manually assigned before calling save()' error.
but that's ok so far.
I then encountered the same problem in the save action of my bookController. But this time, the workaround didn't do the trick.
Any suggestions?
I known, I can rename the id, but then I will have to change all scaffolded views...
That's a feature of databinding. You don't want submitted data to be able to change managed fields like id and version, so the Map constructor that you're using binds all available properties except those two (it also ignores any value for class, metaClass, and a few others).
So there's a bit of a mismatch here since the value isn't managed by Hibernate/GORM but by you. As you saw the workaround is that you need to create the object in two steps instead of just one.
I can't replicate this problem (used Grails 2.0.RC1). I think it might be as simple as a missing equal sign on your static mapping = { (you just have static mapping {)
Here's the code for a domain object:
class Book {
String id
String name
static mapping = {
id generator:'assigned'
}
}
And inside BootStrap.groovy:
def init = { servletContext ->
new Book(name:"test",id:"123abc").save(failOnError:true)
}
And it works fine for me. I see the id as 123abc.
You need to set the bindable constraint to true for your id prop, e.g.
class Employee {
Long id
String name
static constraints = {
id bindable: true
}
}

How to query by relationship and?

I have a grails domain class Character
class Character {
String name
int level
boolean alive
Player player
static constraints = {
name(blank:false, unique:true)
level(min:1)
player(nullable:false)
}
}
I want to query for a character with a specified player, where the value of alive is "true". I tried using the following, but it
Character.findByPlayerAndAliveEqual(p, true)
But it generates an exception
No signature of method: static java.lang.Character.findByPlayerAndAliveEqual() is applicable for argument types: (com.thestreetsgame.security.Player, java.lang.Boolean) values: [com.thestreetsgame.security.Player : 1, true]
I've also tried findByPlayerAndAlive, with the same result. How can I make this gorm query work?
Oops, the important part of the exception just jumped out at me.
java.lang.Character
I was trying to do a lookup on the core java class instead of my domain class. Need to always use the fully qualified name, or change the name of the class.
For the time being I've fully qualified the reference, and it is working.

Grails: No signature of method findAll() is applicable for argument types: String, ArrayList

I'm new to grails and receive the following error:
No signature of method: Something.findAll() is applicable for argument types: (java.lang.String, java.util.ArrayList) values: [from Something AS s WHERE s.some_number LIKE ?, [%asdf%]]"
The error occurs when I run test-app. It occurs in the following place:
SomethingVO[] findBySomeNumber(String searchString) {
searchString = "%"+searchString+"%"
return Something.findAll("from Something AS s WHERE s.some_number LIKE ?",[searchString]).collect {
new SomethingVO(it);
}
}
The class Something is a domain object:
package some.project.domain
class Something{
static belongsTo = [product:Product, productVersion:ProductVersion]
Long id
String name
String someNumber
static constraints = {
product (nullable:true)
productVersion (nullable:true)
}
}
Where is the mistake?
(I use Grails 1.2.4)
findAll is not mocked during unit testing and that's why your code isn't working. You need to manually add a mock for the call before running your test (mockFor could help you with that). This applies if your use HQL or Criterias (which I would recommend over pure HQL).
Alternatively it's possible that you could solve your problems using dynamic finders. Dynamic finders and the other dynamic ORM methods (save, get, count, ..) are in most(?) cases mocked when you call mockDomain(Something) in your unit test. They are also generally easier to use than HQL (imho).
Update:
Thanks to Fletch for pointing out that not all dynamic finders are mocked. An example of a dynamic finder that won't be mocked is this: Something.findAllWhereSomeNumberInList([1, 2, 3]).
The HQL you use in your code could be rewritten like this using dynamic finders:
Something.findBySomeNumberLike(searchString)
Xlson's answer is correct, however there is an alternative "cutting edge" solution you can try, which is currently in testing status. See http://grails.1312388.n4.nabble.com/New-approach-to-mocking-domain-classes-in-Grails-unit-tests-td2529895.html

Setting Grails domain id in Bootstrap.groovy

Is it possible to explicitly set the id of a domain object in Grails' Bootstrap.groovy (or anywhere, for that matter)?
I've tried the following:
new Foo(id: 1234, name: "My Foo").save()
and:
def foo = new Foo()
foo.id = 1234
foo.name = "My Foo"
foo.save()
But in both cases, when I print out the results of Foo.list() at runtime, I see that my object has been given an id of 1, or whatever the next id in the sequence is.
Edit:
This is in Grails 1.0.3, and when I'm running my application in 'dev' with the built-in HSQL database.
Edit:
chanwit has provided one good solution below. However, I was actually looking for a way to set the id without changing my domain's id generation method. This is primarily for testing: I'd like to be able to set certain things to known id values either in my test bootstrap or setUp(), but still be able to use auto_increment or a sequence in production.
Yes, with manually GORM mapping:
class Foo {
String name
static mapping = {
id generator:'assigned'
}
}
and your second snippet (not the first one) will do the job (Id won't be assigned when passing it through constructor).
What I ended up using as a workaround was to not try and retrieve objects by their id. So for the example given in the question, I changed my domain object:
class Foo {
short code /* new field */
String name
static constraints = {
code(unique: true)
name()
}
}
I then used an enum to hold all of the possible values for code (which are static), and would retrieve Foo objects by doing a Foo.findByCode() with the appropriate enum value (instead of using Foo.get() with the id like I wanted to do previously).
It's not the most elegant solution, but it worked for me.
As an alternative, assuming that you're importing data or migrating data from an existing app, for test purposes you could use local maps within the Bootstrap file. Think of it like an import.sql with benefits ;-)
Using this approach:
you wouldn't need to change your domain constraints just for
testing,
you'll have a tested migration path from existing data, and
you'll have a good data slice (or full slice) for future integration tests
Cheers!
def init = { servletContext ->
addFoos()
addBars()
}
def foosByImportId = [:]
private addFoos(){
def pattern = ~/.*\{FooID=(.*), FooCode=(.*), FooName=(.*)}/
new File("import/Foos.txt").eachLine {
def matcher = pattern.matcher(it)
if (!matcher.matches()){
return;
}
String fooId = StringUtils.trimToNull(matcher.group(1))
String fooCode = StringUtils.trimToNull(matcher.group(2))
String fooName = StringUtils.trimToNull(matcher.group(3))
def foo = Foo.findByFooName(fooName) ?: new Foo(fooCode:fooCode,fooName:fooName).save(faileOnError:true)
foosByImportId.putAt(Long.valueOf(fooId), foo) // ids could differ
}
}
private addBars(){
...
String fooId = StringUtils.trimToNull(matcher.group(5))
def foo = foosByImportId[Long.valueOf(fooId)]
...
}

Resources