2009-12-22 116 views
0

我有一種虛假的問題,我需要做一個@NamedQuery與其他表,一些簡單的事情加入。JPA @NamedQuery有兩個表,可能嗎?

但在我所有的@NamedQuery我只處理我的映射對象/表。

舉例來說,在我的對象/表映射汽車

@NamedQuery(name = Cars.GET_AVAILABLE_CARS, 
    query = "select c.id from Cars c where c.status = (select d.status from CarStatus d where d.color=red)") 

我試圖使用方法:@SecondaryTables但現在沒有成功。

另外一個工作是將其他表格的所有內容作爲參數給出,但我認爲這在性能上不會很好。

像:

@NamedQuery(name = Cars.GET_AVAILABLE_CARS, query = 
    "select c.id from Cars c where c.status = :" + CarStatusParam) 

任何提示嗎?

在此先感謝

+0

除非您可以使用繼承,@SecondaryTable或映射你的對象映射到第二個表(@OneToOne,...),那麼你將不得不使用@NamedNativeQuery。爲了進一步幫助您,我需要更多地瞭解表結構以及您正在使用的JPA提供程序(例如,EclipseLink具有可以實現此功能的擴展,並允許您使用存儲過程(@NamedStoredProcedureQuery))。 – 2009-12-23 09:00:34

+0

查詢有什麼問題? Cars和CarSatus如何定義和映射? 'd.color = red'無效。 'd.color ='red''可能是正確的。 – 2013-07-26 06:47:15

回答

2

命名查詢可以使用一個API查詢可以使用一切,所以可以清楚地做子查詢。 JPA的哪個實現?

1

你試圖做的不是連接。這是一個子選擇。就性能而言,它與預先得到參數一樣有效。

但是,如果您堅持要使用子查詢,那麼JPA查詢語言會支持它。因爲它支持連接。 Take a look here(在 7.11 8.11子查詢)。

1

我猜你有這樣的事情:

@Entity 
public class Cars{ 
    private String status; 
    //... something else 
} 

@Entity 
public class CarStatus{ 
    private String status; 
    private String color; 
    //... something else 
} 

如果是這樣,改變這種

@Entity 
public class Cars{ 
    private CarStatus status; //<--THIS!! 
    //... something else 
} 

@Entity 
public class CarStatus{ 
    private String color; 
    //... something else 
} 

,然後更新您的NamedQuery這樣:

query ="select c.id from Cars c where c.status.color = 'red'" 

如果我錯誤和表不應該這樣相關,那麼你應該改變你的查詢tu使用聯接,而不是子查詢。事情是這樣的:

query = "select c.id from Cars c join CarStatus d where c.status = d.status and d.color = 'red'"