JPA SET IDENTITY_INSERT not working

前端 未结 2 2019
臣服心动
臣服心动 2021-01-19 16:50

I want to run this query from JPA from my code. But its not working.

Please help.

SET IDENTITY_INSERT \"+tableName+\" ON

UP

相关标签:
2条回答
  • 2021-01-19 16:58

    This and this have helped me and I have got this working as below.

    Also from this link I got the answer that JPA will not support DDL operation.

    If anyone can add to this answer, that will be great too.

    EntityTransaction tx = entityManager.getTransaction();
    
    try {
    // entitiesMap hold the entity class/table name pairs which have autoincrement primary keys in the sql server database
    if(entitiesMap.containsKey(entityName)){
        String tableName = entitiesMap.get(entityName);
        Session session = (Session) entityManager.getDelegate();
        session.connection().createStatement().execute("SET IDENTITY_INSERT [dbo]." + tableName + " ON");
    }
    
    tx.begin();
    entityObject = jpaTemplate.merge(entity);
    tx.commit();
    
    if(entitiesMap.containsKey(entityName)){
        String tableName = entitiesMap.get(entityName);
        Session session = (Session) entityManager.getDelegate();
        session.connection().createStatement().execute("SET IDENTITY_INSERT [dbo]." + tableName + " OFF");
    }
    
    return entityObject;
    } catch (Exception e) {
    }finally{
    }
    
    0 讨论(0)
  • 2021-01-19 17:14

    You don't want quotes around the table name.

    ="SET IDENTITY_INSERT "+tableName+" ON"

    0 讨论(0)
提交回复
热议问题