ColdFusion ORM试图插入到标识列中

时间:2015-07-25 03:14:06

标签: hibernate orm coldfusion coldfusion-11

我对ColdFusion ORM有一个奇怪的问题,它在创建EntityNew()然后EntitySave()后尝试在我的标识列中插入一个值。以下是特定的属性定义:

property name='StaffAdminID'
    fieldType='id'
    type='numeric'
    ormType='integer'
    generator='identity'
    setter=false
    insert=false
    update=false;

以下是创建新记录的代码:

transaction {
    LOCAL.staffAdmin = EntityNew('StaffAdmins');
    LOCAL.staffAdmin.setYear( REQUEST.user.getYear() );
    LOCAL.staffAdmin.setStaff( LOCAL.staff );
    LOCAL.staffAdmin.setAdmin( LOCAL.admin );
    LOCAL.staffAdmin.setAddedOn( Now() );
    LOCAL.staffAdmin.setAddedBy( SESSION.username );
    LOCAL.staffAdmin.setAddedID( REQUEST.user.getStaffID() );
    EntitySave( LOCAL.staffAdmin );
}

这是Hibernate日志:

2015-07-24 21:49:20,108 [ajp-bio-8014-exec-6] Hibernate DEBUG org.hibernate.SQL - 
    insert 
    into
        StaffAdmins
        (AddedOn, AddedBy, AddedID, YearID, StaffEnrollmentID, AdminEnrollmentID, StaffAdminID, StaffID, AdminID) 
    values
        (?, ?, ?, ?, ?, ?, ?, ?, ?)

导致以下错误:

coldfusion.orm.hibernate.HibernateSessionException:
[Macromedia][SQLServer JDBC Driver][SQLServer]
Cannot insert explicit value for identity column in
table 'StaffAdmins' when IDENTITY_INSERT is set to OFF

正如您所看到的,它正在尝试使用我假设的StaffAdminID插入null列。我不确定发生了什么,我甚至尝试在Component上设置dynamicInsert=true。任何想法都会很棒!感谢

3 个答案:

答案 0 :(得分:0)

实际上你应该把主键的mssql表作为IDENTITY(1,1)  所以它增加自己,然后你不需要给一个staffadminid

答案 1 :(得分:0)

试试这个

property name="StaffAdminID" fieldtype="id" column="StaffAdminID" generator="identity" setter="false";

答案 2 :(得分:0)

答案归结为StaffAdminID字段中的值是否需要自动生成。由于您是从请求范围插入ID,我认为您不会生成新的StaffAdmin条目,因此您可以完全删除该字段上的IDENTITY而不会出现问题(如果在某处可以自动生成ID,这并不意味着StaffAdmin表也需要IDENTITY

但是,如果您确实需要自动生成它们,那么我会在您的交易IDENTITY_INSERT之前的某个地方转EntitySave,如下所示:

transaction{
    LOCAL.staffAdmin = EntityNew('StaffAdmins');
    LOCAL.staffAdmin.setYear( REQUEST.user.getYear() );
    LOCAL.staffAdmin.setStaff( LOCAL.staff );
    LOCAL.staffAdmin.setAdmin( LOCAL.admin );
    LOCAL.staffAdmin.setAddedOn( Now() );
    LOCAL.staffAdmin.setAddedBy( SESSION.username );
    LOCAL.staffAdmin.setAddedID( REQUEST.user.getStaffID() ); 

    // This statement should turn IDENTITY_INSERT on for the rest of the transaction
    identityOn = queryExecute( 'SET IDENTITY_INSERT StaffAdmin ON' );

    // Save the entity (while IDENTITY_INSERT is on)
    EntitySave( LOCAL.staffAdmin );

    // Turn IDENTITY_INSERT off again for two reasons:
    // 1. Prevents accidental ID inserts by others
    // 2. Prevents an error being thrown when trying to set IDENTITY_INSERT on for another table
    identityOff = queryExecute( 'SET IDENTITY_INSERT StaffAdmin OFF' );
}

以上假设您的application.datasource已设置 - 如果不明显将选项结构添加到queryExecute并指定datasource属性

有关再次关闭ID插入的第二个原因(上图)的说明,请参阅remarks from Microsoft