org.hibernate.ObjectNotFoundException: No row with the given identifier exists解决

本文详细解析了在使用Hibernate框架时遇到的ObjectNotFoundException异常原因及其解决方案。通过调整配置文件中的hbm2ddl.auto属性,避免了每次执行操作时重新创建表,确保了数据的正确加载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

环境

 

Eclipse Jee-indigo + Hibernate 3.2 + JDK 1.6.31

 

问题

 

Hibernate load某个对象出现如下异常:

 

org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.oracle.entities.Dictionary#1]
	at org.hibernate.impl.SessionFactoryImpl$2.handleEntityNotFound(SessionFactoryImpl.java:419)
	at org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:154)
	at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:143)
	at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:174)
	at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:190)
	at com.oracle.entities.Dictionary_$$_javassist_0.getName(Dictionary_$$_javassist_0.java)
	at com.oracle.entities.HBTest.testMapLoad(HBTest.java:130)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
	at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
	at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
	at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
	at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

 


 

解决

 

报这个异常很大原因是该对象不存在,在testMap这个方法里保存数据,在testMapLoad这个方法里加载数据,思考下为什么数据会不存在。原来是在Dictionary.hbm.xml这个配置文件中做了如下配置:

<property name="hbm2ddl.auto">create</property>

这样配置后就会出现每次执行操作都会重新创建表,在testMapLoad里只加载没插入数据自然就找不到了。于是解决办法这样:先执行testMap这个方法保存数据,然后把

<property name="hbm2ddl.auto">create</property>改成

<property name="hbm2ddl.auto">update</property>,再重新运行testMapLoad自然就不会报此异常了。

 

//代码片段
@Test
	public void testMap(){

		Map words=new HashMap();
		words.put("hello", "你好");
		words.put("ok", "是");
		
		Dictionary dic=new Dictionary();
		dic.setName("eng");
		dic.setPublisher("william");
		dic.setWords(words);
		
		session.save(dic);
	}
	@Test
	public void testMapLoad(){
		Dictionary dic = new Dictionary();
		dic = (Dictionary)session.load(Dictionary.class, 1);
		System.out.println(dic.getName());
		Map words=new HashMap();
		words = dic.getWords();
		System.out.println(words.isEmpty());
		System.out.println(words.get("ok"));
	}


 

参考资料

 

http://yushengxiang.iteye.com/blog/818829

 

http://wj98127.iteye.com/blog/189723

 

2025-08-14 09:55:57.343 -ERROR 17 --- [nio-9130-exec-4] c.c.t.i.c.AbstractCustomExceptionHandler@printExceptionStack: [[L4Fg]] [http-nio-9130-exec-4] cn.com.truthvision.iacp.pojo.exception.ObjectNotFoundException: county[110105] not found [L4Fg] cn.com.truthvision.iacp.pojo.exception.ObjectNotFoundException: county[110105] not found [L4Fg] at cn.com.truthvision.iacp.biz.smartpark.service.service.AdministrativeDivisionService.lambda$queryCounty$16(AdministrativeDivisionService.java:226) [L4Fg] at java.base/java.util.Optional.orElseThrow(Optional.java:403) [L4Fg] at cn.com.truthvision.iacp.biz.smartpark.service.service.AdministrativeDivisionService.queryCounty(AdministrativeDivisionService.java:225) [L4Fg] at cn.com.truthvision.iacp.biz.smartpark.service.controller.AdministrativeDivisionController.lambda$queryCounty$3(AdministrativeDivisionController.java:91) [L4Fg] at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1768) [L4Fg] at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1144) [L4Fg] at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:642) [L4Fg] at java.base/java.lang.Thread.run(Thread.java:1583) 2025-08-14 09:55:57.344 - INFO 17 --- [nio-9130-exec-4] c.c.t.i.b.s.s.c.ResponseBodyPrinter @beforeBodyWrite: request method[GET] uri[http://100.67.190.21:9130/smart-park-service/administrative-division/country?callerUid=60271788-0021-0000-0000-000000000000&countyCode=110105] body[] response body[{"code":404000004,"message":"county[110105] not found"}] 2025-08-14 09:56:03.606 -DEBUG 17 --- [ scheduling-1] c.c.t.i.b.s.service.service.TaskService @scheduleTask: scheduleTask: runningTask(0) 2025-08-14 09:56:03.609 - INFO 17 --- [ scheduling-1] p6spy @logSQL: time: 0 ms | statement-0 | sql: SELECT 1 2025-08-14 09:56:03.612 - INFO 17 --- [ scheduling-1] p6spy @logSQL: time: 0 ms | statement-0 | sql: /* select generatedAlias0 from TaskProgressPO as generatedAlias0 where ( generatedAlias0.status in (:param0) ) and ( generatedAlias0.lastUpdate<:param1 ) */ select taskprogre0_."task_id" as task_id1_29_, taskprogre0_."code" as code2_29_, taskprogre0_."complete_time" as complete3_29_, taskprogre0_."ex_msg" as ex_msg4_29_, taskprogre0_."last_update" as last_upd5_29_, taskprogre0_."progress" as progress6_29_, taskprogre0_."result" as result7_29_, taskprogre0_."start_time" as start_ti8_29_, taskprogre0_."status" as status9_29_ from t_task_progress taskprogre0_ where (taskprogre0_."status" in ('created' , 'running')) and taskprogre0_."last_update"<'2025-08-14T09:55:33.606+0800' limit 1 2025-08-14 09:56:03.612 -DEBUG 17 --- [ scheduling-1] c.c.t.i.b.s.service.service.TaskService @scheduleTask: scheduleTask: found task(0) 2025-08-14 09:56:03.639 -DEBUG 17 --- [ scheduling-1] c.c.t.i.b.s.s.service.ImportTaskService @scheduleTask: scheduleTask: runningTask(0) 2025-08-14 09:56:03.643 -DEBUG 17 --- [ scheduling-1] .t.i.b.s.s.s.ImportProprietorTaskService@scheduleTask: scheduleTask: runningTask(0) 详细解释日志,并分析问题原因
最新发布
08-15
### 解决Java项目中`org.hibernate`包缺失问题 在Java项目开发过程中,如果遇到`java.lang.ClassNotFoundException: org.hibernate.engine.jndi.JndiNameException`或其他类似的Hibernate类找不到错误,通常是因为项目的依赖配置不完整或未正确引入必要的库文件。 以下是解决此问题的具体方法: #### 1. **确认Maven/Gradle依赖** 确保在项目的构建工具(如Maven或Gradle)中已正确定义了Hibernate的核心依赖项。对于Maven项目,应在`pom.xml`中添加如下依赖[^1]: ```xml <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.2.4.Final</version> </dependency> ``` 如果需要支持二级缓存功能,则还需额外引入EhCache的相关依赖: ```xml <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.4.3</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>4.2.4.Final</version> </dependency> ``` 此外,为了日志记录的支持,建议加入SLF4J API作为日志框架的一部分: ```xml <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.1</version> </dependency> ``` 完成以上操作后,执行`mvn clean install`命令重新编译并下载所需依赖。 --- #### 2. **手动导入Jar包** 如果不使用Maven或Gradle管理依赖关系,可以手动将所需的Hibernate JAR文件复制到项目的`lib`目录下,并将其添加至classpath中。具体步骤包括但不限于以下内容: - 下载Hibernate发布版压缩包(例如`hibernate-release-4.2.4.Final.zip`),从中提取核心模块及其可选组件。 - 将必要文件夹内的`.jar`文件拷贝到工程路径下的`lib`子目录。 - 配置IDE环境变量以加载这些外部资源。 注意:这种方法虽然可行但维护成本较高,推荐优先采用自动化工具来简化流程控制。 --- #### 3. **处理特定场景引发的异常** 当数据库查询返回的结果为空时可能会触发`ObjectNotFoundException`,对此可以通过调整实体映射策略加以规避。比如,在定义关联字段时显式声明忽略丢失对象的行为模式[^2]: ```java @ManyToOne(cascade = CascadeType.REFRESH, fetch = FetchType.EAGER) @NotFound(action=NotFoundAction.IGNORE) // 设置忽略无法匹配的情况 private PropertyEnt propertyEnt; ``` 而对于SQL语法结构上的瑕疵所引起的运行期报错——即ORA-00907缺少闭合圆括号的情形,则需仔细校验动态拼接语句逻辑是否存在遗漏之处[^3]。修正后的XML片段形式可能类似于下面这样: ```xml <!-- 待审核 --> <if test="activeTab != null and activeTab == 0"> <!-- 班长登录 --> <if test="userRole != null and userRole == 2"> AND WORK_STATE IN (9) </if> </if> ``` 通过上述手段能够有效缓解由不同原因造成的各类常见故障现象。 --- #### 总结 综上所述,针对`org.hibernate`命名空间不可见的问题主要可以从以下几个方面入手排查与修复:一是核查POM文档或者build.gradle脚本里的条目设置;二是考虑直接嵌入官方发布的二进制单元副本;三是依据实际业务需求合理运用高级特性从而减少不必要的冲突风险。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值