JPA SET IDENTITY_INSERT无效

时间:2015-03-09 15:03:59

标签: java sql-server sql-server-2008 jpa

我想从我的代码中从JPA运行此查询。但它不起作用。

请帮忙。

SET IDENTITY_INSERT "+tableName+" ON

更新

确切的代码行是

Query query = entityManager.createNativeQuery("SET IDENTITY_INSERT   [tableName] ON");
int updated = query.executeUpdate();

它为更新提供0。不对此行执行给出任何错误。但是当在此之后尝试插入时,它会给出约束违规异常,如下所示。

2015-03-09 15:46:52,922 WARN  org.hibernate.util.JDBCExceptionReporter.logExceptions:233 - SQL Error: 544, SQLState: 23000
2015-03-09 15:46:52,923 ERROR org.hibernate.util.JDBCExceptionReporter.logExceptions:234 - Cannot insert explicit value for identity column in table 'table_name' when IDENTITY_INSERT is set to OFF.
2015-03-09 15:46:52,924 ERROR org.hibernate.event.def.AbstractFlushingEventListener.performExecutions:324 - Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: could not insert: [com.entities.EntityName]

2 个答案:

答案 0 :(得分:2)

Thisthis帮助了我,我的工作如下。

同样从这个link我得到了JPA不支持DDL操作的答案。

如果有人可以添加这个答案,那也会很棒。

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{
}

答案 1 :(得分:0)

您不希望表名附近有引号。

=“SET IDENTITY_INSERT”+ tableName +“ON”