2012-01-13 4 views
3

Grails 도메인 클래스에 문제가 있습니다. net.sf.json.JSONObject에서 도메인 클래스 객체를 작성하기 위해 생성자를 재정의했습니다. 이것은 컨트롤러를 통해 객체를 구별 할 때 잘 동작합니다. 그럼 테스트 케이스를 통해 인스턴스를 시도하고, 예외가 있어요 : (java.lang.String의) 값 : 인수의 형태에 적용 profileplugin.Contact.addToEmails() 메소드의Grails addTo * 생성되지 않음

없음 서명을 [뭔가를 @ 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); }; 
    }; 

} 

그리고 여기가 마침내, 여기에 (아래 피드백을받은 후) 작업 코드의 버전입니다 ...

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

예를 들어 소스 JSON 문자열이고 :

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

} 
+0

당신이 우리가 살펴 수있는 샘플 프로젝트를 압축 할 수 벤에

def emails = [] etc... 

덕분? – Mengu

답변

2

websites: String, 끝 부분에 ,이 없어야합니다. 컴파일에 놀랐습니다.

String 클래스에 대해 hasMany 관계를 설정하는 것은 쉽지 않습니다 (데이터베이스 트랜잭션을 만들고 싶지 않으면 전화, 팩스, 전자 메일 및 웹 사이트에 대한 도메인 클래스를 만드는 것이 더 좋습니다). 그것은 컨트롤러 내부에 있어야합니다, 당신은 도메인 클래스 내부에 비즈니스 로직을를 추가해서는 안, 더 중요한 것은 또한 아마

this.emails.add(it) 

:

다음
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[] 

    ... 

} 

및 사용 :이 방법을 다시 작성해야 서비스 또는 일부 외부 클래스 (src 디렉토리 아래).

는 편집 : 실제로는 제대로 컴파일되지 않습니다, 올바른 구문은 다음과 같습니다

+0

자바와 그루비 모두에서지도, 배열 또는 목록 정의의 후미 쉼표는 괜찮습니다. 감사합니다. –

+0

감사합니다. – fixitagain

+1

"도메인 클래스 내에 비즈니스 논리를 추가하면 안됩니다"- 잘못된 부분 인 IMNSHO. 물론, Hibertate는 설정자의 논리를 방해하지만 비즈니스 로직은 * 도메인 클래스의 * 정의입니다. –

2

도메인 클래스에 모의 객체를 정의 했습니까? see