JPA SET IDENTITY_INSERT无法正常工作 [英] JPA SET IDENTITY_INSERT not working

查看:425
本文介绍了JPA SET IDENTITY_INSERT无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

请帮助.

SET IDENTITY_INSERT "+tableName+" ON

更新

确切的代码行是这个

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

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

It gives 0 for the updated. Does not give any error on this line execution. But when try to insert after this, it gives constraint violation exception like below.

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]

推荐答案

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

也通过此链接我得到的答案是JPA将不支持DDL操作.

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

这篇关于JPA SET IDENTITY_INSERT无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆