Hiberate problems, jdbc IDENTITY_INSERT is set to OFF Hiberate problems, jdbc IDENTITY_INSERT is set to OFF sql-server sql-server

Hiberate problems, jdbc IDENTITY_INSERT is set to OFF


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:

  1. Pick a different generator class, such as "native"
  2. Set IDENTITY_INSERT to "ON"


try to change the type of the generator class from 'assigned' to 'identity', it worked for me


Here's something that worked for me. Adapt as needed.

@SuppressWarnings("deprecation")public static void saveWithOverwrittenId(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();        throw new RuntimeException(e);    } finally {        if (identityInsertSetToOn) {            try {                session.connection().createStatement().execute("SET IDENTITY_INSERT "+tableName+" OFF");            } catch (SQLException e) {                throw new RuntimeException(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.