문제

I am trying to create 2 domain classes User and MailBox

There will be 2 Mailbox for each User, one is sent, another is inbox.

I've tried multiple ways of solving this:

1 - (fails with a mapping exception)

Mailbox {
}

User {
    static hasOne=[inbox:Mailbox, sent:Mailbox]
}

2 - (perfectly fine until i tries to use it, then the value of sent becomes null at all times)

Mailbox {
    static belongsTo = [user: User]
}

User {     
    Mailbox inbox
    Mailbox sent
}

3 - (when I tried to create a new User by: new User(inbox: new Mailbox(), sent: new Mailbox()).save() it fails)

Mailbox {
    static belongsTo = [user: User]
}

User {
    static mappedBy = [inbox: 'id', sent: 'id']
    Mailbox inbox
    Mailbox sent   
}

What is the proper way of creating this relationship?

도움이 되었습니까?

해결책

How about having a base class for the mailboxes? The base class can have all the mail box properties. The child classes can be empty for now and can be filled in if you discover the need for inbox or sent box specific properties as you develop your application further.

This should work.

class InboxMailBox extends MailBox {
    static belongsTo = [user: User]
}

class SentMailBox extends MailBox {
    static belongsTo = [user: User]
}

class User {
    InboxMailBox inbox
    SentMailBox sent
}

다른 팁

A bidirectional association can only map from one property to another property, you can't have a property mapping to multiple properties:

class Mailbox {
    static belongsTo = [user: User]
    static mappedBy = [user: 'one']
}

class User {
    Mailbox inbox
    Mailbox sent

    static constraints = {
        inbox(nullable: true)
        sent(nullable: true)
    }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top