Hiberate Problems, Jdbc Identity_insert Is Set To Off
Solution 1:
You cannot insert into an identity column in SQL Server unless "IDENTITY_INSERT" is set to "ON". Since your generator class is "assigned", Hibernate is assuming that you are setting an explicit value for "id" in Java before saving the object and that Hibernate can directly insert the value into the database. You need to either:
- Pick a different generator class, such as "native"
- Set IDENTITY_INSERT to "ON"
Solution 2:
try to change the type of the generator class from 'assigned' to 'identity', it worked for me
Solution 3:
Here's something that worked for me. Adapt as needed.
@SuppressWarnings("deprecation")
publicstaticvoidsaveWithOverwrittenId(Session session, Object entity) {
String tableName = entity.getClass().getSimpleName();
boolean identityInsertSetToOn = false;
try {
session.connection().createStatement().execute("SET IDENTITY_INSERT "+tableName+" ON");
identityInsertSetToOn = true;
session.beginTransaction();
session.saveOrUpdate(entity);
session.getTransaction().commit();
} catch (SQLException e) {
session.getTransaction().rollback();
thrownewRuntimeException(e);
} finally {
if (identityInsertSetToOn) {
try {
session.connection().createStatement().execute("SET IDENTITY_INSERT "+tableName+" OFF");
} catch (SQLException e) {
thrownewRuntimeException(e);
}
}
}
}
In my case, the SQL Server table had the same name as the Entity class. For you, this is probably not true. One solution, then, would be to ask the table name as a parameter.
Solution 4:
Change the type of the generator class
BEFORE
<idname="id"type="long"><columnname="Id" /><generatorclass="assigned" /></id>
AFTER
<idname="id"type="long"><columnname="Id" /><generatorclass="native" /></id>
Now this will work!
Solution 5:
It would be best to use wrapper classes like Integer instead of primitive int.
Taking your code as an example
<classname="orm.generated.Report" table="Report" schema="dbo" catalog="DatabaseName">
<idname="id"type="java.lang.Integer"><columnname="ID" /><generatorclass="assigned" /></id>
Post a Comment for "Hiberate Problems, Jdbc Identity_insert Is Set To Off"