Hibernate 多对一外键默认 0 [英] Hibernate Many-To-One Foreign Key Default 0

查看:25
本文介绍了Hibernate 多对一外键默认 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表,其中父对象具有可选的多对一关系.问题是该表设置为默认 fkey 列为 0.

I have a table where the the parent object has an optional many-to-one relationship. The problem is that the table is setup to default the fkey column to 0.

选择时,使用 fetch="join" 等-- fkey 上的默认值 0 用于反复尝试从另一个表中为 ID 0 选择.当然这不存在,但是我如何告诉 Hibernate 将 0 值视为与 NULL 相同——在获取不存在的关系时不循环 20 多次?

When selecting, using fetch="join", etc-- the default of 0 on the fkey is being used to try over and over to select from another table for the ID 0. Of course this doesn't exist, but how can I tell Hibernate to treat a value of 0 to be the same as NULL-- to not cycle through 20+ times in fetching a relationship which doesn't exist?

<many-to-one name="device" lazy="false" class="Device" not-null="true" access="field" cascade="none" not-found="ignore">
<column name="DEVICEID" default="0" not-null="false"/>

推荐答案

我能够通过创建一个扩展内置 Long 类型的 id-long 类型来解决这个问题,但是如果从 SQL 返回的 id 为 0,则返回 null反而.这在我们的数据库中保留了默认 0 的余量,同时让休眠停止进行延迟获取.

I was able to fix this by creating an id-long type which extends the built in Long type, but if the id returned from SQL was 0, return null instead. This kept the allowance of default 0s in our DB while getting hibernate to stop doing lazy fetches.

public class IdentifierLongType extends LongType implements IdentifierType {

@Override
public Object get(ResultSet rs, String name) throws SQLException {
    long i = rs.getLong(name);
    if (i == 0) {
        return null;
    } else {
        return Long.valueOf(i);
    }
}

}

强制执行显式默认值 0 的原因是 Oracle 处理索引和空值的方式很奇怪,这表明使用显式值与 'where col is [not] null' 相比具有更好的查询性能

The reason for enforcing explicit default 0 is that Oracle handles indexing and null values oddly, suggesting better query performance with explicit values vs. 'where col is [not] null'

这篇关于Hibernate 多对一外键默认 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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