2017-03-07 25 views
1

我想在JPQL中使用LIKE關鍵字過濾BigDecimal標識。我使用EclipseLink。將BigDecimal轉換爲字符串以便在JPQL查詢中使用LIKE過濾一些BigDecimal標識

假設我們有ID:197718,182123,182912,123456,並且我想從表中提取entity.id(如%18%)的所有行。如果操作成功,則結果將爲:182123,182912

我的查詢會。

public List<MyEntity> getFilteredMyEntity(String idStr) { 
    return entityManager.createQuery("select m from MyEntity m where m.id like :idStr") 
         .query.setParameter("idStr", "%" + idStr+ "%") 
         .getResultList(); 
} 

讓我們說,我調用這個方法這樣才能得到一個包含「18」的ID的所有實體:

List<MyEntity> entities = getFilteredMyEntity("18"); 

但我得到一個例外,因爲我不能比較的BigDecimal與一個字符串。所以,我必須將此BigDecimal轉換爲字符串

有沒有在jpql(非本機查詢)將BigDecimal轉換爲字符串的方法嗎?類似於to_char()。

+0

'String#valueOf'和'BigDecimal#toString'似乎是很明顯的選擇。那些不適合你? –

+2

[JPQL like表達式需要int值](http://stackoverflow.com/q/22558476/5221149)或[JPA Like Operator with Integer](http://stackoverflow.com/q/5535084/5221149) 。兩者都表示同樣的事情:在查詢文本中將'm.id'強制轉換爲字符串,所以'like'在兩側都有字符串。 – Andreas

+0

請檢查我的答案,我使用JPQL測試它,它工作正常 –

回答

1

可以在JPQL像旁邊做(我測試了我的身邊,並與我一起工作)

注:我使用JPA 2.1和Hibernate提供

public List<MyEntity> getFilteredMyEntity(String idStr) { 
    return entityManager.createQuery("SELECT m FROM MyEntity m WHERE CAST(m.id AS string) LIKE :idStr") 
     .setParameter("idStr", "%" + idStr+ "%").getResultList(); 
} 

這裏是另一種方式使用原生查詢

public List<MyEntity> getFilteredMyEntity(String idStr) { 
    return entityManager.createNativeQuery("SELECT m FROM MyEntity m WHERE CAST(m.id AS varchar(10)) LIKE :idStr") 
     .setParameter("idStr", "%" + idStr+ "%").getResultList(); 
} 
+0

@NellyJunior我注意到我使用hibernate與JPA,實際上我測試了它,但也沒有用任何其他提供者測試它,無論如何你可以編輯在我的答案中,你看到它會幫助將來的任何人,我會檢查你的編輯,謝謝:) –