问题描述
我有一个父对象有一个可选的多对一关系的表。问题是表被设置为默认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等 - 默认为0 fkey被用来反复尝试从另一个表中选择ID0。当然这并不存在,但是我怎么能告诉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,同时让hibernate停止执行延迟提取。
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处理索引和空值奇怪,表明更好的查询性能,显式值与'col col [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'
这篇关于休眠多对一外键默认为0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!