【问题标题】:Grails addTo* not getting createdGrails addTo* 没有被创建
【发布时间】:2012-01-13 01:01:10
【问题描述】:

Grails 域类有问题。我正在重写构造函数以从 net.sf.json.JSONObject 构建域类对象。当我通过控制器实例化对象时,这很好用。然后我尝试通过一个测试用例实例化它,并得到了一个异常:

无方法签名:profileplugin.Contact.addToEmails() 适用于参数类型:(java.lang.String) 值:[something@something.com]

我还应该指出,这似乎适用于某些类,但不适用于其他类。非常令人沮丧——我是 Grails 的新手,所以如果有人能指出我正确的方向,我将不胜感激。

这是我的域类代码。

package profileplugin

import net.sf.json.JSONObject

class Contact
{
    static hasMany =
    [
        phones: String,
        faxes: String,
        emails: String,
        websites: String,
    ];

    Contact() {};  // standard constructor must be specified, or grails dies
    Contact(JSONObject source)
    {
        source.get('emails').each()         { this.addToEmails(it);   };
        source.get('websites').each()       { this.addToWebsites(it); };
        source.get('phones').each()         { this.addToPhones(it);   };
        source.get('faxes').each()          { this.addToFaxes(it);    };
    };

}

这是一个示例源 JSON 字符串 ...

[
    addresses:[], 
    phones:["(555) 555-7011"], 
    faxes:[], 
    emails:["someone@something.com"], 
    websites:["http://www.google.com"]
]

最后,这是有效的代码版本(在获得以下反馈后):

class Contact
{
    def phones = [];
    def faxes = [];
    def emails = [];
    def websites = [];

    Contact() {};  // standard constructor must be specified, or grails dies
    Contact(JSONObject source)
    {
        print source;

        source.get('phones').each()         { this.phones.add(it);   };
        source.get('emails').each()         { this.emails.add(it);   };
        source.get('websites').each()       { this.websites.add(it); };
        source.get('faxes').each()          { this.faxes.add(it);    };
    };

}

【问题讨论】:

  • 您可以压缩一个示例项目以便我们看一下吗?

标签: json grails groovy


【解决方案1】:

检查你的源代码,你的websites: String, 末尾不应该有, 我很惊讶它编译成功了。

为 String 类放置 hasMany 关系是没有意义的(除非您想在其上进行数据库事务,否则最好为电话、传真、电子邮件和网站创建域类)。你应该这样重写:

package profileplugin

import net.sf.json.JSONObject

class Contact
{

    String[] phones=new String[]
    String[] faxes=new String[]
    String[] emails=new String[]
    String[] websites=new String[]

    ...

}

然后使用:

this.emails.add(it)

另外并且可能更重要的是,您不应该在域类中添加业务逻辑,它应该在您的控制器、服务或某些外部类中(在src 目录下)。

编辑: 实际上它没有正确编译,正确的语法是:

def emails = []
etc...

感谢本

【讨论】:

  • 在 java 和 groovy 中,映射、数组或列表定义中的尾随逗号都可以
  • “你不应该在你的域类中添加业务逻辑” - IMNSHO 这是错误的部分。当然,Hibertate 会干扰 setter 中的逻辑,但业务逻辑是 THE 域类的定义。
  • 您好,感谢您的回复,但您的示例代码无法编译。语法似乎不正确。
  • 通过指定数组大小(def phone = new String[100]),我得到了一个稍微不同的错误。但是同样的问题:没有方法签名:[Ljava.lang.String;.add() 适用于参数类型:(java.lang.String)
  • 好的,我已经让它工作了,部分是基于你的建议。使用工作代码更新帖子。
【解决方案2】:

您是否为域类定义了模拟对象? see

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    相关资源
    最近更新 更多