2016-12-09 96 views
0

我在2小時的研究之後創建了這個主題。JPA select查詢

我想做一個非常簡單的汽車位置代碼,它可以保存,刪除從數據庫中獲取數據。

所以我的問題是我有一個父類名爲Vehicule和2個孩子類:汽車和麪包車。 下面,有

// vehicule 
@Entity 
@Table(name="Vehicule") 
@DiscriminatorColumn(name="vehicule_type") 
@Inheritance 
public class Vehicule implements Serializable{ 
// some constructors setters and getters here 
} 

// car 
@Entity 
@DiscriminatorValue("Car") 
public class Car extends Vehicule{ 
    @Column(name = "number_of_seats") 
    private int nbOfSeats; 
    // some constructors setters and getters here 
} 

// van 
@Entity 
@DiscriminatorValue("Van") 
public class Van extends Vehicule{ 
    @Column(name = "max_weight") 
    private int maxWeight; 
    // some constructors setters and getters here 
} 

我將它們存儲在inheritanceStratregy =單表中的單個表我的3個班的開始。 現在,我想選擇只有汽車或只有麪包車。

我試圖

Query query = em.createQuery("SELECT v FROM Vehicule v WHERE v.vehicule_type = 'Car'"); 
List<Car> list = (List<Car>) query.getResultList(); 

,但我得到

Caused by: java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager: 
The state field path 'v.vehicule_type' cannot be resolved to a valid type. 

我也試過

CriteriaBuilder cb = em.getCriteriaBuilder(); 
CriteriaQuery<Car> q = cb.createQuery(Car.class); 
Root<Car> c = q.from(Car.class); 
ParameterExpression<String> p = cb.parameter(String.class); 

q.select(c).where(cb.equal(c.get("vehicule_type"), p)); 

TypedQuery<Car> query = em.createQuery(q); 
query.setParameter(p, "Car"); 
List<Car> results = query.getResultList(); 

,但我得到

Caused by: java.lang.IllegalArgumentException: The attribute [vehicule_type] is not present in the managed type 

我做錯了什麼?

在此先感謝!

+0

您不需要在條件中附加vehicule_type。 JPA附加它自己,因爲你說選擇從Vehicule ...嘗試SELECT v FROM Vehicule v –

+0

我做了「SELECT v FROM Car v」...「SELECT v FROM Vehicule v」只有在你的車類DiscriminatorValue也是。 –

回答

0

我看不到「Vehicule」實體的完整字段。 但是,如果你有你的VEHICULE表,字段名「vehicule_type」 你UST必須在你的代碼名稱爲「vehiculeType」

指定它只是試圖改變「vehicule_type」到「vehiculeType」

但爲了獲得更多幫助,我認爲您必須提供您的Vehicle實體類的內容。

乾杯

0

是否有名稱vehicule_type的任何字段?我懷疑它不存在,並以某種方式嘗試訪問它導致異常。

0

您不需要在鑑別器值的標準位置插入。 JPA自己做這件事。你只需要選擇正確的實體。

在你的情況下,你應該選擇:「SELECT v FROM Car v」。 如果您在配置中啓用show_sql,您將看到JPA自動添加了aliasXX.vehicule_type ='Car'

+0

它剛剛工作!非常感謝 !!! – Kiwi

+0

不用客氣 –