一次选择现有和非现有的连接实体

时间:2013-01-16 12:49:13

标签: jpa jpql

我的连接表看起来像这样。

EXCHANGE_RATE
------------------------------
ID                  BIGINT  PK
SOURCE_CURRENCY_ID  BIGINT  FK
TARGET_CURRENCY_ID  BIGINT  FK

映射的ExchangeRate.java

public class ExchangeRate {

    protected ExchangeRage() {
        this(null, null);
    }

    // for SELECT NEW
    public ExchangeRate(Currency sourceCurrency, Currency targetCurrency) {
        this.sourceCurrency = sourceCurrency;
        this.targetCurrency = targetCurrency;
    }

    @Id private Long id;
    @ManyToOne private Currency sourceCurrency;
    @ManyToOne private Currency targetCurrency;
}

如何为给定的ExchangeRate列出所有现有和不存在的sourceCurrency

例如,

  1. 有三种货币。 A,B和C.
  2. 已经有从A到B的ExhangeRate
  3. 使用以下方法,如果sourceCurrencyA

    public List<ExchangeRate> listExchangeable(Currency sourceCurrency) {
        //
    }
    

    我如何获得以下列表?

    ExchangeRate {
        id:             0
        sourceCurrency: A
        targetCurrency: B
    },
    ExchangeRate {
        id:             NULL
        sourceCurrency: A
        targetCurrency: C
    }
    

1 个答案:

答案 0 :(得分:0)

必填查询

// get all exchange rates for a source currency
public List<ExchangeRate> listExchangeable(Currency sourceCurrency) {
  Query qry = em.createQuery("select r from ExchangeRate r where 
                                 r.sourceCurrency = :sourceCurrency");
  qry.setParameter("sourceCurrency", sourceCurrency);
  return qry.getResultList();
}

表示给定sourceCurrency的非现有ExchangeRates

Query qry = em.createQuery("select r from ExchangeRate r where 
                                 r.sourceCurrency != :sourceCurrency");