如何在Java服务层访问Grails域类?

发布于 2024-08-30 12:33:08 字数 280 浏览 5 评论 0原文

如何在 Java/Spring 的服务层中使用 grails 域类(在 groovy 中)。

使用 grails MVC 时,一切都很好,因为我可以使用控制器访问域对象并调用 CRUD 和其他动态方法。但是,我想知道是否有一种干净的方法可以从 Java 中做到这一点 - 比如服务层。例如,我可能想开发一个报告框架,其中我需要使用域对象来访问数据库。

我希望问题很清楚。这应该是每个人在合理规模的项目中都必须面临的标准问题。我只是想知道它是如何解决的......也许我在这里遗漏了一些东西。

谢谢。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

我ぃ本無心為│何有愛 2024-09-06 12:33:08

org.codehaus.groovy.runtime.InvokerHelper 使这变得非常简单;请参阅此邮件列表线程: http://grails.1312388.n4.nabble.com/Calling-Dynamic-Finders-on-Domain-Class-via-the-MetaClass-td1596496.html

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

ゞ花落谁相伴 2024-09-06 12:33:08

示例代码片段:

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

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); 
2024-09-06 12:33:08

虽然 InvokerHelper 工作得很好,但如果您有权访问 GORM 类,我会在 GORM 调用周围放置包装函数——然后 Java 类就会看到这一点。

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

这看起来更干净,并且不会在 Java 代码中依赖 Groovy 类。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文