Grails:获取“字段XXX没有默认值”

时间:2016-01-25 03:28:24

标签: grails dns many-to-many default-value sqlexception

我遇到了由两个域类之间的多对多关系引起的奇怪错误。课程如下。当我尝试保存NoteParagraph对象时,我不会立即收到错误:

NoteParagraph np = new NoteParagraph(number: noteNumber, content: noteText)
note.addToChildParagraphs(np).save()

然而,在下一个.save()动作(在一个不相关的对象上),我得到以下错误stacktrace:

Field 'note_paragraph_id' doesn't have a default value. Stacktrace follows:
java.sql.SQLException: Field 'note_paragraph_id' doesn't have a default value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:998)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1901)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2113)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2049)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2034)
at org.grails.datastore.gorm.GormStaticApi$_methodMissing_closure2.doCall(GormStaticApi.groovy:102)

以下是我的课程:

class NoteParagraph {

    String number
    String content
    Note parentNote

    Date dateCreated
    Date lastUpdated

    static belongsTo = Note

    static hasMany = [
        childNotes: Note
    ]

    static constraints = {
    }

    static mapping = {
        content type:'text'
    }
}

和第二个:

class Note {

    Integer noteType
    Integer parentType
    Integer parentId
    String heading

    Date dateCreated
    Date lastUpdated

    static hasMany = [
        childParagraphs: NoteParagraph
    ]

    static constraints = {

    }

    static mapping = {
        heading type:'text'
    }
}

我尝试删除并重新创建我的数据库,正如其他一些线程所建议的那样,这没有帮助。

1 个答案:

答案 0 :(得分:0)

修正:

class NoteParagraph {

    String number
    String content

    Date dateCreated
    Date lastUpdated

    static belongsTo = [parentNote: Note]

    static hasMany = [
        childNotes: Note
    ]

    static constraints = {
    }

    static mapping = {
        content type:'text'
    }
}

当您尝试将NoteParagraph添加到Note时,NoteParagraph实例不是持久的(它已创建但尚未保存在db中)。

尝试改变:

NoteParagraph np = new NoteParagraph(number: noteNumber, content: noteText)
note.addToChildParagraphs(np).save()

为:

note.save(flush: true) //add also this, if note is not persisted
NoteParagraph np = new NoteParagraph(number: noteNumber, content: noteText, parentNote: note).save(flush: true)
note.addToChildParagraphs(np).save()