HasOne和HasMany具有相同的域类和级联保存

时间:2013-08-16 12:22:32

标签: grails gorm

我有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 and hasMany same domain

有人可以帮助我吗?关心并提前感谢。

2 个答案:

答案 0 :(得分: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关系中没有级联保存。

答案 1 :(得分: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
}