Using Hibernate CompositeUserType in JPA Queries

I am using a CompsiteUserType to map a class 'Unit':

class Unit {
  long type;
  Currency currency;
  Currency crossCurrency;
}

where depending on the type of the Value ('Money', 'XRate', ...) the field 'crossCurrency' may be null (eg 'Money' does not have a cross currency).

The 'nullSafeSet' method of the CompositeUserType is implemented as follows:

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 {
    ...
  }
}

Now I have a JPA query that tries to find entities based on their 'Unit':

SELECT p FROM Position WHERE p.unit = :unit

When executing this query Hibernate generates an SQL Query:

SELECT id, ... 
FROM positions p
WHERE (p unit_type, p unit_currency_id, p unit_cross_currency_id)=(?, ?, ?)

In Case the 'Unit' given to the query is a 'Money' then the concrete query is:

SELECT p.id, ...
FROM positions p
WHERE (p.unit_type, p.unit_currency_id, p.unit_cross_currency_id)=('money', 1, null)

In that case no matching rows in the database will be found because the queries 'where clause' checks whether the 'unit_cross_currency_id' equals 'null' which will never match.

Am I doing something wrong here?

How can I use a composite user type with possible null values in a JPA query?

链接地址: http://www.djcxy.com/p/63820.html

上一篇: 在休眠平等中处理空值

下一篇: 在JPA查询中使用Hibernate CompositeUserType