簡體   English   中英

JPA SQL查詢(JPQL)中的字符串搜索運行時錯誤

[英]String search runtime error in JPA SQL query (JPQL)

嘗試通過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());
}

錯誤java.util.UnknownFormatConversionException: Conversion = '''運行時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%' ,以搜索通過上述查詢選擇的全部或其中一條記錄。

  • '%%' -返回所有記錄,但沒有String參數
  • '%s' s'-如果SQL查詢的語句正確,則給出特定記錄

其他所有問題都引起了問題,字符串'%% s%'不是我寫的,但是我需要保留它或通過保持相同的結果來對其進行更改。 我想要的結果是給出所有記錄,但是在接收到String參數時返回該特定記錄。

這里可能存在的問題超出了我的JPA知識范圍。

我剛剛檢查了TypedQuery API,您可以TypedQuery設置參數。

TypedQuery<Object[]> query = connection.createQuery("select t.id, t.one, t.two from Test t where t.one like :one order by t.id", Object[].class);
query.setParamter("one", "%" + s + "%");
List<Object[]> tablelist = query.getResultList();

更新:

好像這兩個條件似乎是分開的,就像其他答案所建議的那樣,您可以通過生成查詢來完成

StringBuilder query = new StringBuilder("select t.id, t.one, t.two from Test t "); 
if (StringUtils.isNotEmpty(s)) { 
    query.append(" where t.one like :one "); 
} 
query.append(" order by t.id");
TypedQuery<Object[]> query = connection.createQuery(query.toString());

我個人將進行這兩個查詢,它將表現更好。 像這樣:

public List<Object[]> collectOne( String param ) {
    TypedQuery<Object[]> query = connection.createQuery("select t.id, t.one, t.two from Test t where t.one like :one order by t.id", Object[].class);
    query.setParamter("one", "%" + param + "%");
    return query.getResultList();
}

public List<Object[]> collectAll() {
    TypedQuery<Object[]> query = connection.createQuery("select t.id, t.one, t.two from Test t order by t.id", Object[].class);
    return query.getResultList();
}

然后,您始終可以擁有可能帶有或不帶有參數的怪異方法:

public List<Object[]> collectOneOrAll( String param ) {
    if ( param == null || param.isEmpty() )
        return collectAll();

    return collectOne( param );
}

暫無
暫無

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

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