14

我正在尝试在遗留数据库(仍然有遗留 PHP 客户端)上实现休眠,并且遇到了一些问题,因为编写原始应用程序的人不知道他们在做什么。

数据库设置为没有任何列可以为空,因此如果没有记录,它们默认外键为 0。此外,它们在表上没有正确的外键,因此有一些具有无效 ID。我没有选择更改架构或将相应的列设为空的选项。

这是我从休眠中得到的错误:

Caused by: org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.tv.platform.domain.Program#0]

我想要的是一种处理这种垃圾的优雅方式,如果该行无效或不存在,该字段将为空,但我没有任何运气在文档中找到如何处理这个问题。

有小费吗?

4

4 回答 4

16

The annotation: @NotFound( action = NotFoundAction.IGNORE )

Does exactly what I was looking for. I found it through here:

Hibernate Many-To-One Foreign Key Default 0

于 2011-04-26T21:21:14.163 回答
2

我认为 Hibernate 不适合解决这类问题。Hibernate 期望您的表中的记录相互关联,并且如果仅有时强制执行外键关系,则实际上无法工作。我无法想象改变或配置 Hibernate 以这种方式运行会很容易——知道如何处理损坏的外键关系。

您可能会从像MyBatis SQLMaps这样的框架中获得更多的好处,您可以在其中提供 SQL 语句以将数据加载到程序外部的文件中,但该框架提供了将SELECT语句链接在一起以加载完整对象图的选项。这样,您可以用逻辑补充 SQL 语句以过滤掉0值。

于 2011-04-26T19:19:01.400 回答
1

我认为拦截器可以解决问题。

于 2011-04-26T19:52:50.440 回答
0

我最近针对具有类似问题的遗留数据库编写了一个 webapp。如果您不想使用多个数据访问框架,您仍然可以使用休眠。我所做的是使用“createSqlQuery”为棘手的部分编写原生 SQL 查询。在某些情况下,我必须将完整的子查询或计算值映射到实体属性,但它可以工作。对于更常规的数据库部分,我仍然可以使用常规的 Hibernate 映射和条件/HQL 查询。

Another thing: maybe you should refrain from using terms like 'no idea what they were doing' or 'muck' a bit. I know it is tempting to view any code left to you by predecessors as inferior, but realize that these people probably did the best they could at the time. Also, your own code is not flawless either, so some humility is in place. Why? For one, people around you might get along with you a bit better if you are not foaming around the mouth all the time about the previous developer(s) who they thought were very knowledgeable. Just a tip.

于 2011-04-26T19:54:26.703 回答