This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Query q = JPA.em().createNativeQuery("SELECT * from post p"); | |
List<Post> posts = (List<Post>)q.getResultList(); |
但是當你執行時,會出現無法轉換的錯誤:ClassCastException occured : [Ljava.lang.Object; cannot be cast to models.Post
這時候你可以在執行createNativeQuery時,給定第二個參數,用來說明要把這次的查詢轉換成某個物件,以上面的範例來說,你可以這樣寫:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Query q = JPA.em().createNativeQuery("SELECT * from post p, Post.class"); | |
List<Post> posts = (List<Post>)q.getResultList(); |
回頭看一下官方的API,當中有特別提到這兩個不同方法的用途,在你執行update或delete時,就用傳sql字串的方式,其他需要作物件轉換的,就用第二種方法:
Query createNativeQuery(String sqlString)
- Create an instance of Query for executing a native SQL statement, e.g., for update or delete.
- Create an instance of Query for executing a native SQL query.
【相關閱讀】
EntityManager API
0 意見:
張貼留言