簡體   English   中英

當我可以通過 Hibernate JPA 和 java 中的等效 int 值查詢時,為什么我不能按字符串值查詢

[英]Why can't I query by String value when I can query by equivalent int value in Hibernate JPA with java

我在工作中得到了一個項目,包括 JPA / Hibernate

例如,我有一個 object 可以說描述為

class SampleObject {
   string value;
   string othervalue;
}

假設數據庫中的值填充了 2 行

表 - SampleObject

  • 第 1 行 - value = "21", othervalue = "some other value"

  • 第 2 行 - value = "31", othervalue = "其他一些值"

我可以編寫一個返回以下行的查詢

Query q = entityManager.createQuery("select s from SampleObject s where value = 21")

我可以編寫一個返回以下行的查詢

Query q = entityManager.createNativeQuery("select * from dbo.SampleObject s where value = 21", SampleObject.class)

但我不能做的是將這些相同的查詢寫為字符串值並返回數據

例 1:

  entityManager.createQuery("select s from SampleObject s where value = '21'")

例 2:

  entityManager.createQuery("select s from SampleObject s where value = :val").setParameter("val", "21")

例 3:

   entityManager.createNativeQuery("select * from dbo.SampleObject s where value = '21'", SampleObject.class)

但正如您所看到的,它存儲為 varchar 並且需要保留為字符串,因此我需要能夠通過字符串進行查詢

免責聲明:

我是 hibernate 的新手 - 非常新......非常非常新!

我應該添加 SQL SSMS 我可以直接通過字符串查詢

我還嘗試使用以下建議之一,但對於上下文,它沒有解決在此處輸入圖像描述

你可以使用:

entityManager.createQuery("select s from SampleObject s where value = :val").setParameter("val", "21", StringType.INSTANCE)

該實現適用於您要傳遞的確切類型。

我必須道歉我有一個舊的連接字符串

我直接在 ssms 中查詢當前數據,而連接字符串正在抓取 java 中的舊數據

我的錯,它一直在工作

通過調試器顯示舊數據

謝謝您的幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM