How do I access the Grails domain classes at the Java service layer?

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

With grails MVC everything is fine as I can use a controller to access domain objects and call CRUD and other dynamic methods. But I'm wondering if there is a clean way to do this from Java - say a service layer. For example, I can design a reporting framework in which I need to use domain objects to access the DB.

Hope the question is clear. This should be a common problem that everyone should have faced in a reasonably sized project. I'm just wondering how to solve this. Maybe I missed something.

thanks.

+2


a source to share


3 answers


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



+2


a source


Sample code snippet:



import my.package.User
import org.codehaus.groovy.runtime.InvokerHelper;


List allInstances = (List)InvokerHelper.invokeMethod(User.class, "list", null)); 


User one=(User)InvokerHelper.invokeMethod(User.class, "get", id); 

      

+1


a source


Where, when InvokerHelper

works well, if you have access to the GORM class, I would put wrapper functions around the GORM calls - then the Java classes will see this.

static String List getAll() { return User.list() }
static String User getByID(long id) { return User.get(id) }

      

This seems cleaner and does not affect the Groovy class in your Java code.

0


a source







All Articles