【发布时间】:2014-01-24 22:43:55
【问题描述】:
当尝试通过 JPA 从数据库中检索表并将其填充到 Table 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());
}
String SQL = String.format("select t.id, t.one, t.two from Test p where p.one like '%%s%' order by p.id",one); 行的运行时错误 java.util.UnknownFormatConversionException: Conversion = '''
问题接缝是'%%s%' 变量中的String SQL。我需要保留'%%s%',以便搜索使用上述查询选择的全部或其中一条记录。
-
'%%'- 返回所有记录,但没有字符串参数 -
'%s'- 如果 SQL 查询的语句是 正确
其他一切都会出现问题,字符串 '%%s%' 不是我写的,但我需要保留它或通过保持相同的结果来更改它。我想要的结果是给出所有记录,但在接收到 String 参数时返回该特定记录。
这里的问题可能超出了我的 JPA 知识范围。
【问题讨论】:
-
你可能需要使用
NameQuery类似"select t.id, t.one, t.two from Test t where t.one like :one order by t.id然后namedQuery.setParameter("one", "%" + s + "%"); -
我可以尝试一个 NameQuery,但是 setParameter 方法只返回该参数指定的一个特定记录。
-
setParameter 只是将参数设置为查询.. 类似于
PreparedStatement中的?。看看我的回答,我们在查询中有:one作为命名参数。
标签: java sql jpa runtime-error