我使用CompsiteUserType来映射类'Unit':
class Unit {
long type;
Currency currency;
Currency crossCurrency;
}
根据值的类型('Money','XRate',...),字段'crossCurrency'可能为空(例如'Money'没有交叉货币)。
CompositeUserType的'nullSafeSet'方法实现如下:
public void nullSafeSet(...) {
Unit unit = (Unit) value;
stmt.setLong(index, unit.type);
if(unit.type == UnitType.MONEY) {
stmt.setLong(index+1, unit.currency.id);
stmt.setNull(index+2, java.sql.Types.BIGINT);
} else if(unit.type == UnitType.XRate) {
stmt.setLong(index+1, unit.currency.id);
stmt.setLong(index+2, unit.crossCurrency.id);
} else {
...
}
}
现在我有一个JPA查询,试图根据他们的“单位”找到实体:
SELECT p FROM Position WHERE p.unit = :unit
执行此查询时,Hibernate会生成SQL查询:
SELECT id, ...
FROM positions p
WHERE (p unit_type, p unit_currency_id, p unit_cross_currency_id)=(?, ?, ?)
如果给查询的'Unit'是'Money',那么具体的查询是:
SELECT p.id, ...
FROM positions p
WHERE (p.unit_type, p.unit_currency_id, p.unit_cross_currency_id)=('money', 1, null)
在这种情况下,数据库中不会找到匹配的行,因为查询'where子句'检查'unit_cross_currency_id'是否等于'null',它们永远不会匹配。
我在这里做错了吗?
如何在JPA查询中使用具有可能空值的复合用户类型?