How to access Grails domain classes in Java service layer?

て烟熏妆下的殇ゞ 提交于 2019-12-09 01:38:05

问题


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.


回答1:


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




回答2:


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); 



回答3:


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.



来源:https://stackoverflow.com/questions/2717098/how-to-access-grails-domain-classes-in-java-service-layer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!