2014-01-09 29 views
1

我有這樣的本地SQL請求:轉換本地SQL到JPQL與內部聯接

SELECT LMC_PARAMETRE.* FROM LMC_PARAMETRE 
    INNER JOIN INTERVENTION ON INTERVENTION.ID_INTV = LMC_PARAMETRE.ID_INTV 
    INNER JOIN REF_SITE ON INTERVENTION.DID_SITE =REF_SITE.ID_SITE 
    WHERE INTERVENTION.DCD_STATUT_INTV = '0' AND REF_SITE.ID_CENT = '097'; 

我喜歡把它轉換成JPQL但「ON」鍵字是不被認可:

JpaQueryBuilder builder = new JpaQueryBuilder(); 
    builder.append("SELECT lmp FROM "+LmcParametre.class.getName()+" AS lmp "); 
    builder.append("INNER JOIN "+Intervention.class.getName()+" AS intv ON "); 
    builder.append("intv.idIntv = lmp.intervention.idIntv "); 
    builder.append("INNER JOIN "+Site.class.getName()+" AS site ON "); 
    builder.append("intv.didSite = site.idSite "); 
    builder.append("WHERE "); 
    builder.append(lt("intervention.statutIntv", String.valueOf(constanteInferieurePretACharger))); 
    builder.append("site.centre.idCent = "+idCentre); 

根據HQL文檔:HQL中的連接是通過使用實體之間的關聯完成的。 但是我不明白這意味着什麼。

感謝

回答

0

假設您已經模擬這些實體正確使用JPA(包括它們的關係),那麼你所有的JPQL將是:「選擇LP從LmcParametre低壓內加入lp.intervention我內連接i.site小號其中s.idSite =:idSite和i.statutIntv =:statut「。

假設你有註冊爲您LmcParametre類命名查詢該JPQL查詢(使用註釋

@NamedQueries({ @NamedQuery(name="myQuery", query = "select lp from LmcParametre lp inner join lp.intervention i inner join i.site s where s.idSite = :idSite and i.statutIntv = :statut") }) 

那麼你可以創建這樣一個類型的查詢:

TypedQuery<LmcParametre> query = entityManager.createNamedQuery("myQuery", LmcParametre.class); 
query.setParameter("idSite", myIdSite); 
query.setParameter("statut", myStatut); 
List<LmcParametre> results = query.getResultList(); 
0

您不能使用在JPA中的ON子句加入。要在JPA中執行JOIN,需要在實體之間進行映射,並在JPQL查詢中使用此關聯。

所以,與其使用:

SELECT lmp FROM LmcParametre AS lmp 
INNER JOIN Intervention AS intv ON intv.idIntv = lmp.intervention.idIntv 
INNER JOIN Site AS site ON intv.didSite = site.idSite 

您需要使用:

SELECT lmp FROM LmcParametre lmp 
JOIN lmp.interventions intv -- you need the "interventions" mapped (@OneToMany?) in LmcParametre 
JOIN intv.site -- you need the "site" mapped in Intervention