jjzjj

java - 由于重复的 GUID,无法将数据库状态与 session org.hibernate.exception.ConstraintViolationException 同步

coder 2024-03-07 原文

我使用 hibernate 在使用自动生成的 GUID 的表中插入数据,但有时插入失败并出现重复的 GUID 异常。

例如:

从 Logs 中,通过打印重复的 GUID“0500edac-0074-4324-3436-31444231342d”,前 2 次尝试插入失败。所用时间如下

     1st attempt :08-27-2018 04:27:00.012,

     2nd attempt :08-27-2018 04:27:01.024,

     3rd attempt was not logged ,as it was successful

但在数据库中,我看到一行 GUID 为“0500edac-0074-4324-3436-31444231342d”,创建时间为“08-27-2018 04:27:01.054”

所以我不确定为什么我在前 2 次尝试中获得异常,然后在第 3 次成功插入。

SQL 表属性:我有一个名为“DataHistory”的 SQL Server 表,其中有一列名为

"DataHistoryGuid" with the following properties uniqueidentifier,ROWGUIDCOL,Primary Key column,newsequentialid .

hibernate 属性: 我正在使用 hibernate 将数据存储在该表中,对于 GUID 列,我正在使用

<id name="dataHistoryGuid" type="java.util.UUID" >
        <column name="DataHistoryGuid"/>
        <generator class="guid"/>
    </id>

异常轨迹如下:

[event.def.AbstractFlushingEventListener:performExecutions:324]
Could not synchronize database state with session 
org.hibernate.exception.ConstraintViolationException: could not 
 insert: [com.testProj.dataprocessor.model.sql.SqlDataHistory] 
  at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94) 
  at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) 
  at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2295) 
  at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2688) 
  at org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:79) 
  at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279) 
  at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263) 
  at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167) 
  at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) 
  at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50) 
  at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027) 
  at org.springframework.orm.hibernate3.HibernateAccessor.flushIfNecessary(HibernateAccessor.java:390) 
  at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:420) 
  at org.springframework.orm.hibernate3.HibernateTemplate.executeWithNativeSession(HibernateTemplate.java:374) 
  at org.springframework.orm.hibernate3.HibernateTemplate.saveOrUpdate(HibernateTemplate.java:748) 
  at com.testProj.dataprocessor.common.sql.hibernate.HibernateSession.upsertDataHistory(HibernateSession.java:505) 
  at com.testProj.dataprocessor.common.sql.SqlStore.upsertDataHistory(SqlStore.java:92) 
  at com.testProj.dataprocessor.common.sql.SqlStore$$FastClassByCGLIB$$18d897d8.invoke(<generated>) 
  at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191) 
  at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:700) 
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149) 
  at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:77) 
  at com.testProj.dataprocessor.model.performance.Profiler.profile(Profiler.java:15) 
  at sun.reflect.GeneratedMethodAccessor160.invoke(Unknown Source) 
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
  at java.lang.reflect.Method.invoke(Method.java:498) 
  at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:627) 
  at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:616) 
  at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:64) 
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) 
  at org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint.proceed(MethodInvocationProceedingJoinPoint.java:77) 
  at com.testProj.dataprocessor.common.sql.SqlRetryPolicy.retry(SqlRetryPolicy.java:20) 
  at sun.reflect.GeneratedMethodAccessor161.invoke(Unknown Source) 
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
  at java.lang.reflect.Method.invoke(Method.java:498) 
  at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethodWithGivenArgs(AbstractAspectJAdvice.java:627) 
  at org.springframework.aop.aspectj.AbstractAspectJAdvice.invokeAdviceMethod(AbstractAspectJAdvice.java:616) 
  at org.springframework.aop.aspectj.AspectJAroundAdvice.invoke(AspectJAroundAdvice.java:64) 
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) 
  at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89) 
  at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) 
  at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:635) 
  at com.testProj.dataprocessor.common.sql.SqlStore$$EnhancerByCGLIB$$f3a323cc.upsertDataHistory(<generated>) 
  at com.testProj.dataprocessor.dao.DataDAO.updateDataHistory(DataDAO.java:88) 
  at com.testProj.dataprocessor.eventhandler.DataHistoryEventHandler.doWork(DataHistoryEventHandler.java:34) 
  at com.testProj.dataprocessor.eventhandler.DataHistoryEventHandler.updateDiagnosticsHistory(DataHistoryEventHandler.java:28) 
  at com.testProj.dataprocessor.DataProcessorService.doWork(DataProcessorService.java:37) 
  at com.testProj.dataprocessor.DataProcessorService.process(DataProcessorService.java:24) 
  at com.testProj.dataprocessor.DataProcessorService.process(DataProcessorService.java:80) 
  at com.testProj.dataprocessor.DataProcessorService.postDataEventSync(DefaultDataProcessorService.java:41) 
  at com.testProj.dataprocessor.DataProcessorService.postDataEvent(DefaultDataProcessorService.java:36) at sun.reflect.GeneratedMethodAccessor272.invoke(Unknown Source) 
  at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 
  at java.lang.reflect.Method.invoke(Method.java:498) 
  at org.apache.cxf.service.invoker.AbstractInvoker.performInvocation(AbstractInvoker.java:173) 
  at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:89) 
  at org.apache.cxf.jaxws.JAXWSMethodInvoker.invoke(JAXWSMethodInvoker.java:60) 
  at org.apache.cxf.service.invoker.AbstractInvoker.invoke(AbstractInvoker.java:75) 
  at org.apache.cxf.interceptor.ServiceInvokerInterceptor$1.run(ServiceInvokerInterceptor.java:58) 
  at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) 
  at java.util.concurrent.FutureTask.run(FutureTask.java:266) 
  at org.apache.cxf.workqueue.SynchronousExecutor.execute(SynchronousExecutor.java:37) 
  at org.apache.cxf.interceptor.ServiceInvokerInterceptor.handleMessage(ServiceInvokerInterceptor.java:106) 
  at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:236) 
  at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:109) 
  at Caused by: java.sql.SQLException: Violation of PRIMARY KEY constraint 'PK_DataHistory_on_DataHistoryGuid'. Cannot insert duplicate key in object 'dbo.DataHistory'. The duplicate key value is (0500edac-0074-4324-3436-31444231342d). 
  at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:372) 
  at net.sourceforge.jtds.jdbc.TdsCore.tdsErrorToken(TdsCore.java:2988) 
  at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2421) 
  at net.sourceforge.jtds.jdbc.TdsCore.getMoreResults(TdsCore.java:671) 
  at net.sourceforge.jtds.jdbc.JtdsStatement.processResults(JtdsStatement.java:613) 
  at net.sourceforge.jtds.jdbc.JtdsStatement.executeSQL(JtdsStatement.java:572) 
  at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.executeUpdate(JtdsPreparedStatement.java:727) 
  at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105) 
  at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:105) 
  at org.hibernate.jdbc.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:46) 
  at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2275) ... 68 more

假设:

1.正如 Sql Server 网站提到的,创建的 Guid 中有十亿分之一是重复的,所以我不希望重复出现在我的表中。

最佳答案

虽然问题集中在 Hibernate 上,但跟踪中的以下行表明数据库正在拒绝插入。

Caused by: java.sql.SQLException: Violation of PRIMARY KEY constraint 'PK_DataHistory_on_DataHistoryGuid'. Cannot insert duplicate key in object 'dbo.DataHistory'. The duplicate key value is (0500edac-0074-4324-3436-31444231342d).

与其说是 SQL Server 或 Hibernate 的问题,不如说这是一个设计问题。如果一个自动生成的 UUID 作为 DataHistory 表中的 PRIMARY KEY 是您的目标, 那么你最好使用数据库来实现这一点,而不是使用 Hibernate(或者更糟,推出你自己的解决方案)。 这是因为数据库旨在避免值冲突,如果指定了 UNIQUE INDEXPRIMARY KEY

参见 SQL UNIQUE Constraint

您可以使用 PRIMARY KEY DEFAULT (NEWID()) 创建自动生成的 UUID。 如果以后需要使用UUID,那么在创建后使用非主键值来选择值。

示例表:

CREATE TABLE dbo.DataHistory
(
    DatahistoryGuid uniqueidentifier PRIMARY KEY DEFAULT (NEWID()),
    history_row integer NOT NULL,
    data_stuff  nvarchar(4000) NOT NULL,
    created_date datetime2 DEFAULT (GETDATE())
);

尝试在 Hibernate 中将 insertable 属性设置为 false。对数据库默认的所有列执行此操作。例如:

@Column(name = "DatahistoryGuid", insertable=false)
@Column(name = "created_date", insertable=false)

这会产生类似于以下的 SQL:

INSERT INTO dbo.DataHistory (history_row, data_stuff)
VALUES (1234, 'Joe Bloggs');

参见 Related Question

要获取 DatahistoryGuid 值,请使用 SELECT 语句:

SELECT DatahistoryGuid from dbo.DataHistory where history_row = 1234;

SQL Fiddle Example

关于java - 由于重复的 GUID,无法将数据库状态与 session org.hibernate.exception.ConstraintViolationException 同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57683500/

有关java - 由于重复的 GUID,无法将数据库状态与 session org.hibernate.exception.ConstraintViolationException 同步的更多相关文章

  1. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  2. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  3. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  4. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

  5. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  6. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  7. ruby - 无法覆盖 irb 中的 to_s - 2

    我在pry中定义了一个函数:to_s,但我无法调用它。这个方法去哪里了,怎么调用?pry(main)>defto_spry(main)*'hello'pry(main)*endpry(main)>to_s=>"main"我的ruby版本是2.1.2看了一些答案和搜索后,我认为我得到了正确的答案:这个方法用在什么地方?在irb或pry中定义方法时,会转到Object.instance_methods[1]pry(main)>defto_s[1]pry(main)*'hello'[1]pry(main)*end=>:to_s[2]pry(main)>defhello[2]pry(main)

  8. ruby - 无法在 60 秒内获得稳定的 Firefox 连接 (127.0.0.1 :7055) - 2

    我使用的是Firefox版本36.0.1和Selenium-Webdrivergem版本2.45.0。我能够创建Firefox实例,但无法使用脚本继续进行进一步的操作无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055)错误。有人能帮帮我吗? 最佳答案 我遇到了同样的问题。降级到firefoxv33后一切正常。您可以找到旧版本here 关于ruby-无法在60秒内获得稳定的Firefox连接(127.0.0.1:7055),我们在StackOverflow上找到一个类

  9. ruby - 安装 Ruby 时遇到问题(无法下载资源 "readline--patch") - 2

    当我尝试安装Ruby时遇到此错误。我试过查看this和this但无济于事➜~brewinstallrubyWarning:YouareusingOSX10.12.Wedonotprovidesupportforthispre-releaseversion.Youmayencounterbuildfailuresorotherbreakages.Pleasecreatepull-requestsinsteadoffilingissues.==>Installingdependenciesforruby:readline,libyaml,makedepend==>Installingrub

  10. ruby-on-rails - 无法让 rspec、spork 和调试器正常运行 - 2

    GivenIamadumbprogrammerandIamusingrspecandIamusingsporkandIwanttodebug...mmm...let'ssaaay,aspecforPhone.那么,我应该把“require'ruby-debug'”行放在哪里,以便在phone_spec.rb的特定点停止处理?(我所要求的只是一个大而粗的箭头,即使是一个有挑战性的程序员也能看到:-3)我已经尝试了很多位置,除非我没有正确测试它们,否则会发生一些奇怪的事情:在spec_helper.rb中的以下位置:require'rubygems'require'spork'

随机推荐