How to access Grails domain classes in Java service layer?
How can I use grails domain classes (which is in groovy) in service layer which is in Java/Spring.
When using the grails MVC, 开发者_JAVA技巧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.
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
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);
Where as 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 that.
static String List getAll() { return User.list() }
static String User getByID(long id) { return User.get(id) }
That seems cleaner and doesn't put a dependency on a Groovy class in your Java code.
精彩评论