JPA:需要多对多查询帮助

时间:2010-06-26 13:50:57

标签: java hibernate jpa jpql

我有四个涉及查询的实体,我遇到了一些麻烦。关系如下:Exchange----*Contract*----*Combo----*Trade和(简化)实体如下:

@Entity
public class Exchange implements Serializable {
    @Id(name="EXCHANGE_ID")
    private long exchangeId;

    @Column
    private String exchangeShortName;
}


@Entity
public class Contract implements Serializable { 
        @Id
        private long contractId;

        @Column
        private String contractName;

        @ManyToOne
        @JoinColumn(name="EXCHANGE_ID")
        private Exchange exchange;

        @ManyToMany
        @JoinTable(name="CONTRACT_COMBO",
                        joinColumns = { @JoinColumn(name="CONTRACT_ID") },
                        inverseJoinColumns = {@JoinColumn(name="COMBO_ID")})
        private Set<Combo> combos;

        @Column(name = "ACTIVE_FLAG")
        private String activeFlag;
}

@Entity
public class Combo implements Serializable {

        @Id
        @Column(name="COMBO_ID")
        private Integer id;

        @ManyToMany
        @JoinTable(name="CONTRACT_COMBO",
                        joinColumns = { @JoinColumn(name="COMBO_ID") },
                        inverseJoinColumns = {@JoinColumn(name="CONTRACT_ID")})
        private Set<Contract> legs;

        @OneToMany(mappedBy = "combo")
        private Set<Trade> trades;    
}

@Entity
public class Trade implements Serializable {
        @Id
        @Column(name="TRADE_ID")
        private long tradeId;

        @Column(name="REFERENCE")
        private String reference;

        @ManyToOne
        @JoinColumn(name="COMBO_ID")
        private Combo combo;
}

我想得到一个特定交易所的所有交易清单,我无法与MEMBER OF合作。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:10)

试试这个

select distinct t 
  from Trade t
  join t.combo c
  join c.legs l
  join l.exchange e
 where e.exchangeShortName = 'whatever'

答案 1 :(得分:1)

没有真正优化,但我认为这应该可以解决问题:

Long exchangeId = Long.valueOf(5324623L);
List<Trade> trades = em.createQuery("select T from Trade T where T in " +
    "(select distinct C from Combo c where c member of " +
        "(select e.combos from Exchange e where e.id = :id) " +
    ")").setParameter("id", exchangeId).getResultList();