views:

309

answers:

1

How can I use grails domain classes (which is in groovy) in service layer which is in Java/Spring.

When using the grails MVC, everything is fine as I can use controller to access domain objects and call CRUD and other dynamic methods on them. But, what I am wondering is is there a clean way to do it from Java - say the service layer. For example, I may want to develop a reporting framework where I need to use domain objects to access the DB.

I Hope the question is clear. This should be a standard problem that everybody must have faced in a reasonably sized project. I am just wondering how it is solved..maybe I am missing something here.

thanks.

A: 

org.codehaus.groovy.runtime.InvokerHelper makes this pretty straightforward; see this mailing list thread: http://grails.1312388.n4.nabble.com/Calling-Dynamic-Finders-on-Domain-Class-via-the-MetaClass-td1596496.html

Burt Beckwith
Thanks for the answer. However, after trying the following code in a main class within the grails application -(List<SecUser>)InvokerHelper.invokeMethod(SecUser.class, "list", null)I am getting the "MissingMethodException" which seems logical as there is no "list" method in SecUser domain class.Can you please explain how should I get hold of the "actual" domain object so that I can use the above method on it to access dynamic methods on it ?Thanks
batmannavneet
Do you mean that you ran this from the commandline in a class with a main() method? That won't work - the Grails application has to be running. InvokerHelper just finds the metaclass method for you and invokes it as if you called it from Groovy, but that depends on everything being wired up. To test this you could create a temporary controller that calls your Java class and call the controller from a browser.
Burt Beckwith
Thanks Burt.This works.But what I trying to do is access grails domain class and their CRUD methods from standalone java programs (main method).Is there a way to do that? I can think of several scenarios where there may be need to access the DAO classes in standalone java programs. Now if in grails using GORM, domain classes are the DAO classes, there must be a way to access them in a standalone manner (maybe wire grails application context before calling methods). Can you please suggest of a way to do that, maybe with an example ? Thanks a lot.
batmannavneet
You could look at "Standlone GORM" which was introduced in 1.1; see http://grails.org/1.1+Release+Notes
Burt Beckwith
Will try it. Thanks.
batmannavneet