2014-04-01 95 views
0

我有這個查詢在mysql中成功運行,但我試圖將它寫爲JPA查詢,並且不斷收到錯誤。這是我的桌子。如何將此SQL查詢寫入JPA查詢

Table 1: business_accounts{id, business_name} 
Table 2: work_locations{location_id, name, contractor_id } 
//contractor_id on Table2 is the foreign key matched to id on table 1. 

我的SQL查詢是我想去的地方,從表1的id等於從表2和contractor_id返回BUSINESS_NAME的所有值,其中name =「都柏林」這是在MySQL的工作我的SQL查詢:

SELECT b.business_name FROM work_locations w 
inner join business_accounts b on b.id=w.contractor_id where name="Carlow" 

這裏是我在JPA中採取的方法,它不工作。任何建議表示讚賞。由於

String countyName="Dublin"; 

     Query myQuery2 = em.createQuery("SELECT b FROM business_accounts b join " 
       + "w where b.id=w.contractor_id and w.name=:countyName"); 

     myQuery2.setParameter("countyName", countyName); 

回答

0
  1. 您需要創建相應的表中正確的實體。 a。 Business_Account entity

b。 Work_Location是另一個

c。您可以選擇爲a之間的連接創建單獨的連接表。和b。我會建議,但它是你的偏好。

基於a。和b。試一下這幾行 -

String countyName="Dublin"; 
final TypedQuery<String> query = entityManager 
      .createQuery(
        "Select distinct b.business_name from Business_Account b, IN(b.id) location where b.id=location and location.name =:countyName", String.class); //$NON-NLS-1$ 
    query.setParameter("countyName", countyName); //$NON-NLS-1$ 
+0

感謝您的幫助 – kellzer

0

試試下面的代碼:

  1. 使用createNativeQuery
  2. SELECT b.business_name替代的選擇B
  3. 添加實體類與查詢將返回類型。

    String QUERY = "SELECT b.business_name FROM business_accounts b join w where b.id=w.contractor_id and w.name=?)"; 
    
    List list = em.createNativeQuery(QUERY, ENTITY_CLASS_HERE.class) 
        .setParameter(1, countyName) 
        .getResultList();