views:

83

answers:

2

I have four entities that are involved in a query that I'm having a little trouble with. The relationship is as follows : Exchange----*Contract*----*Combo----*Trade and the (simplified) entities are as follows:

@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;
}

I want to get a list of all trades for a particular exchange which I can't quite get to work with MEMBER OF. Any help would be appreciated.

A: 

Not really optimized, but I think this should do the trick:

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();
seanizer
Almost, but I think you missed the link to Contract.
+1  A: 

Try this

select distinct t 
  from Trade t
  join t.combo c
  join c.legs l
  join l.exchange e
 where e.exchangeShortName = 'whatever'
MacTouch
Great - works perfectly.