0

我有 2 个域类;其中最前面的代表一个电子邮件地址,其中包含用户名和电子邮件地址本身。另一个类代表一封电子邮件,带有主题、发件人(一个电子邮件地址)和收件人(电子邮件地址列表):

class EmailMessage {
    static hasMany = [ to: EmailAddress ]
    EmailAddress from
    String subject
}

class EmailAddress {
    String name
    String address
}

但是这段代码并没有像我预期的那样工作:

EmailMessage msg = new EmailMessage()
msg.from = new EmailAddress(name: "User 1", address: "user1@domain.com")
[new EmailAddress(name: "User 2", address: "user2@domain.com"), new EmailAddress(name: "User 3", address: "user3@domain.com")].each {
    msg.addToTo(it)
}
msg.subject = "Asunto"
msg.save(failOnError: true)

我收到此错误:

| Error 2013-08-14 21:08:40,362 [localhost-startStop-1] ERROR util.JDBCExceptionReporter  - La columna "FROM_ID" no permite valores nulos (NULL)
NULL not allowed for column "FROM_ID"; SQL statement: insert into email_message (id, version, from_id, subject) values (null, ?, ?, ?) [23502-164]
| Error 2013-08-14 21:08:40,375 [localhost-startStop-1] ERROR context.GrailsContextLoader  - Error initializing the application: could not insert: [prueba.EmailMessage];
SQL [insert into email_message (id, version, from_id, subject) values (null, ?, ?, ?)]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not insert: [prueba.EmailMessage]
Message: could not insert: [prueba.EmailMessage]; SQL [insert into email_message (id, version, from_id, subject) values (null, ?, ?, ?)]; constraint [null];
nested exception is org.hibernate.exception.ConstraintViolationException: could not insert: [prueba.EmailMessage]

我不知道这是否可以做到,或者级联保存不能像我想的那样工作。

我认为我在每个班级中都尝试了 hasMany、belongsTo 等的所有组合,但没有成功。

我也读过这个主题,但它没有按预期工作Grails hasOne 和 hasMany same domain

任何人都可以帮助我吗?提前致以问候和感谢。

4

2 回答 2

1

不幸的是,您必须先保存您的from,然后才能保存父母。

EmailMessage msg = new EmailMessage()
msg.from = new EmailAddress(name: "User 1", address: "user1@domain.com")
if (!msg.from.save(flush: true)) {
    log.error("message could not be saved: " + msg.from.errors)
}
[new EmailAddress(name: "User 2", address: "user2@domain.com"), new EmailAddress(name: "User 3", address: "user3@domain.com")].each {
    msg.addToTo(it)
}
msg.subject = "Asunto"
msg.save(failOnError: true)

在 1:1 关系中没有级联保存。

于 2013-08-16T12:38:20.983 回答
1

这在标准内存数据库中对我有用

class EmailMessage {
    static hasMany = [ to: EmailAddress ]
    EmailAddress from
    String subject

    static mapping = {
        from cascade: "save-update" //Pretty sure this is unnecessary
    }
}

class EmailAddress {
    String name
    String address

    static belongsTo = EmailMessage
}
于 2013-08-16T13:33:46.193 回答