1. 程式人生 > >hibernate用like進行模糊查詢時不能寫單引號!!!

hibernate用like進行模糊查詢時不能寫單引號!!!

今天在用hibernate進行like查詢時,遇到了sql語句類似這樣的:
'xxx'      'xxx%'     '%xxx'    '%xxx%'

每種情況都要考慮的時候,直接寫查詢不出結果(我帶單引號查不出結果)

其中SQL SERVER2014中:

SQL語句為:

select p.p_order, p.id

from order_product p

where (p.flange_pie_staff like '7' or p.flange_pie_staff like '7,%' or p.flange_pie_staff like '%,7' or p.flange_pie_staff like '%,7,%')

and p.fit_finish is null and (p.status_id=8 or p.status_id =9);

javawebHQL 為:

注意紅色部分

public static List<Object[]> selectPOder(int staffId) {

//--根據員工id查詢到產品序號

Session session = null;

try {

session = HibernateSessionFactory.getSession();

//此處查id就足夠了,但是隻查id的時候會報錯 java.lang.String cannot be cast to [Ljava.lang.Object

// 情況描述:在執行sql查詢取其返回的資料時出現的;我用的是陣列來取它的Result,其他地方都好好的;但在某些地方就不對!

// 出現原因:sql語句執行的查詢結果只有一列時就會出現該問題!當有多個列時用陣列取沒有問題,如果只有一列會預設為string或者其他型別!

// 解決辦法:  查詢的時候多取一列..OrderProduct

String find = "select p.POrder, p.id from OrderProduct p ";

String sql = " where (p.flangePieStaff like ? or p.flangePieStaff like ? or p.flangePieStaff like ? or p.flangePieStaff like ?) "

+ "and p.fitFinish is null and (p.statusId=8 or p.statusId =9) ";

Query query = session.createQuery(find+sql);

// query.setString(0, "%" + staffName + "%");

//假如給17,27,37……員工派工,那麼7號員工一定不能接到任務,需要做處理

String que0 = "'" +staffId+ "'";//        '7'

String que1 = "'" +staffId+ ",%'";//      '7,%'

String que2 = "'%," +staffId+ "'";//      '%,7'

String que3 = "'%," +staffId+ ",%'";//    '%,7,%'

query.setString(0, que0);

query.setString(1, que1);

query.setString(2, que2);

query.setString(3, que3);

@SuppressWarnings("unchecked")

List<Object[]> list = query.list();

System.out.println("que0="+que0+"   que1="+que1+"   que2="+que2+"   que3="+que3);

System.out.println("selectPOder  ="+list.size());

return list;

} catch (HibernateException e) {

e.printStackTrace();

return null;

} finally {

if (session != null) {

session.close();

}

}

}

糾結了一早上,百度了查了很多,最終解決了:原因如下:

SQL中用單引號是正確的,但是在hibernate中進行模糊查詢時,單引號是不能加上的

還記得上面紅色的程式碼嗎?把單引號去掉就好了:

String que0 = "" +staffId+ "";//        '7'

String que1 = "" +staffId+ ",%";//      '7,%'

String que2 = "%," +staffId+ "";//      '%,7'

String que3 = "%," +staffId+ ",%";//    '%,7,%'

結果:

Hibernate: select orderprodu0_.p_order as col_0_0_, orderprodu0_.id as col_1_0_ from Legend.dbo.order_product orderprodu0_

where (orderprodu0_.flange_pie_staff like ? or orderprodu0_.flange_pie_staff like ? or orderprodu0_.flange_pie_staff like ?

or orderprodu0_.flange_pie_staff like ?) and (orderprodu0_.fit_finish is null) and (orderprodu0_.status_id=8 or orderprodu0_.status_id=9)

que0=7   que1=7,%   que2=%,7   que3=%,7,%

selectPOder  =1


在此記錄一個坑。群裡大佬們都說我的方式選的不好,沒見過連用4個like的查詢,讓我用正則表示式,在此抱歉,小弟剛學javaweb,

並且對資料庫是一竅不通啊。我會慢慢學習進步的,如有幫助請點贊,如果更好的辦法請評論。