2012-04-09 135 views
0

我試圖從'Execution'表中檢索'Vulcano'表中的最後5個插入數據,我使用EclipseLink調用此查詢的Facade類此時此刻;如何使用Java中的JPA檢索表中的最後2條記錄

這是我使用的Facade類的一部分;

public ArrayList<ExecutionPOJO> getLatestsVulcanoExecutions() { 
    ArrayList<ExecutionPOJO> vulcanoExecutions = new ArrayList<ExecutionPOJO>(); 
    //SELECT x FROM Magazine x order by x.title asc, x.price desc 

    **List<Execution> excutionVulcanoList = em.createQuery("select s from Execution s order by s.vulcano_idVulcanoID desc limit 2 ").getResultList();** 

如果我使用上面的查詢我得到這個錯誤:

Caused by: java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager: 
Exception Description: Syntax error parsing the query [select s from Execution s order by s.vulcano desc limit 2], line 1, column 50: syntax error at [limit]. 
Internal Exception: MismatchedTokenException(80!=-1) 

但是,如果我取消該限制標籤我得到這個錯誤;

Caused by: Exception [EclipseLink-8021] (Eclipse Persistence Services - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.JPQLException 
Exception Description: Error compiling the query [select s from Execution s order by s.vulcano desc], line 1, column 36: invalid ORDER BY item [s.vulcano] of type [uk.ac.aston.tomtom.entity.Vulcano], expected expression of an orderable type. 

@Entity 
public class Execution implements Serializable { 
    ... 
@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY) 
private int idExecution; 

@ManyToOne(targetEntity = Vulcano.class) 
private Vulcano vulcano; 

*//Few others @ManyToOne 
//also @oneToMany* 

    public Vulcano getVulcano() { 
    return vulcano; 
} 

public void setVulcano(Vulcano vulcano) { 
    this.vulcano = vulcano; 
    } 

//other getter and setter 
} 

這是另一個實體;

@Entity 
public class Vulcano implements Serializable { 
    ... 
@Id 
@GeneratedValue(strategy = GenerationType.IDENTITY) 
private int idVulcano; 

@OneToMany(targetEntity=Execution.class, mappedBy="vulcano", cascade=CascadeType.ALL) 
private List<Execution> executions; 

    public List<Execution> getExecutions() { 
    return executions; 
} 

public void setExecutions(List<Execution> executions) { 
    this.executions = executions; 
} 

//other getters and setters 

回答

0

嘗試的

SELECT * FROM Magazine x order by x.title asc, x.price desc 

代替

SELECT x from Magazine x ... 
+0

將無法​​使用星形,因爲它拋出一個錯誤; 異常說明:解析查詢的語法錯誤[select * from s.vulcano desc的執行順序],第1行,第7列:意外的標記[*]。 – user1321704 2012-04-09 11:38:50

+0

@ user1321704:選擇您想要閱讀的列,例如「雜誌訂購按標題asc選擇col1,col2,col3,price desc' – 2012-04-09 11:46:55

0

限制不是JPQL的一部分,因此不能使用。相反,您可以在查詢上調用setMaxResults來限制返回的結果。

或者您可以使用原生SQL查詢,其中Select *將使用EntityManager createNativeQuery api而不是createQuery工作。

相關問題