Grails save()后的空ID

时间:2015-08-28 20:03:47

标签: hibernate grails null save flush

得到一个奇怪的错误,并放弃谷歌搜索解决我的问题的答案。这是我的域名

class UserTest {

    User user
    Integer testId
    String testAgency
    String testType
    Date testDate

    static mapping = {
        table 'user_test'
        id generator: 'identity', name: 'testId', type: 'long'
        testId column: 'test_id'
        version false
    }

    static constraints = {
        testAgency(blank: true, nullable: true)
        testType(blank: true, nullable: true)
        testDate(blank: true, nullable: true)
    }
}

这是我创建表格的SQL脚本

CREATE TABLE user_test (
   test_id int NOT NULL IDENTITY(1,1), 
   test_agency varchar(128) NULL,
   test_type varchar(128) NULL,
   test_date datetime NULL,

   user_id int NULL foreign key references user_data(user_id),

   PRIMARY KEY (test_id)
)

以及我试图保存在UserController

的地方
def saveTest(String id) {
    def user = User.findByUserId(id)
    def test_to_add = new UserTest(testAgency:params.testAgency,
                                   testType:params.testType,
                                   testDate:params.testDate,
                                   user:user)
    user.addToTests(test_to_add)
    user.save(flush:true, failOnError:true)
    user.refresh()
    redirect(action:'profile', id:user.userId)
}

但是我收到了错误

Class
    org.hibernate.AssertionFailure
Message
    null id in UserTest entry (don't flush the Session after an exception occurs)

突出显示行user.save(flush:true, failOnError:true)。我做过一堆谷歌搜索,找不到任何有用的东西。有没有人看到为什么testId的IDENTITY(1,1)性质不会自动递增?

1 个答案:

答案 0 :(得分:1)

试试这个

def saveTest(String id) {
def user = User.findByUserId(id)
def test_to_add = new UserTest(testAgency:params.testAgency,
                               testType:params.testType,
                               testDate:params.testDate,
                               user:user).save(failOnError: true)
user.addToTests(test_to_add)

redirect(action:'profile', id:user.userId)
}