當試圖通過JPA來檢索數據庫中的表,並填寫到表SWT窗口小部件(org.eclipse.swt.widgets.Table
),我在執行下面的Java代碼得到一個轉換錯誤:字符串搜索運行時錯誤
String SQL = String.format("select t.id, t.one, t.two from Test t where t.one like '%%s%' order by t.id",one); //variable one is defined as a parameter of the method (whole method not included here for simplicity)
//this is the code that uses the SQL variable above
EntityManager connection = DB.Connection().createEntityManager(); //the EntityManagerFactory
TypedQuery<Object[]> query = connection.createQuery(SQL, Object[].class); /*gives the same as cast (TypedQuery<Object[]>) */
List<Object[]> tablelist = query.getResultList();
connection.close();
SWTtable.removeAll(); //clears all the elements in the table
for (Object[] row : tablelist) {
final TableItem item = new TableItem(SWTtable, SWT.None);
item.setData(row[0]);
item.setText(0, row[1].toString());
}
錯誤java.util.UnknownFormatConversionException: Conversion = '''
上運行時用於線路String SQL = String.format("select t.id, t.one, t.two from Test p where p.one like '%%s%' order by p.id",one);
問題接縫是在String SQL
可變'%%s%'
。我需要保留'%%s%'
,以便搜索使用上面的查詢選擇的全部或一個記錄。
'%%'
- 返回所有記錄,但沒有字符串參數'%s'
- 給出了一個具體的記錄,如果在SQL查詢語句是 正確
其他的一切給出了一個問題,該字符串'%% s%'不是我寫的,但我需要保留它或通過保持相同的結果來改變它。我想要的結果是給所有記錄,但在收到String參數後返回該特定記錄。
這裏有什麼問題超出了我的JPA知識範圍。
您可能需要使用'NameQuery'像'「選擇t.id ,t.one,t.two from Test t where t.one like:one order by t.id' and then'namedQuery.setParameter(「one」,「%」+ s +「%」)'; –
NameQuery我可以嘗試,但一個setParameter方法只返回一個由該參數指定的特定記錄 –
setParameter只是將參數設置爲查詢類似'PreparedStatement'中的'?'。看看我的答案,我們有':one'在查詢中作爲一個命名參數。 –