netbeans - issue with like in hibernate hql -


i'm developping method takes parameter criterion research in query , text of beginning of value of criterion each times test i'm getting empty list , need please

public arraylist<article> getarticlebycritere(string critere, string txt){                arraylist list = new arraylist<article>();                list=null;                string cr;         try {             this.session = hibernateutil.getsessionfactory().opensession();             org.hibernate.transaction tx = session.begintransaction();          if(critere.equals("référence"))             cr="refa";         else if(critere.equals("désignation"))             cr="designation";         else if(critere.equals("famille"))             cr="famille";         else if(critere.equals("code"))             cr="codearticle";         else             cr = "sousfamille";         string query = "from article :critere :debut";        list = (arraylist<article>) session.createquery(query).setstring("critere", cr).setstring("debut", txt + "%").list();               tx.commit();             system.out.println("ok");             session.close();         } catch (exception e) {             system.out.println(" getarticlebyfamdesign échoué" + e);         }         return list;           } 1 me find what's problem here !! 

you can pass values query parameters. can't pass rando parts of query, column names.

so code should be:

string query = "from article " + cr + " :debut"; list = (list<article>) session.createquery(query)                               .setstring("debut", txt + "%")                               .list(); 

also, not following points.

query.list() returns list, , documentation doesn't guarantee list arraylist. shouldn't cast result arraylist. , in fact, have no reason @ that. why care concrete implementation of list. matters it's list. methd should return list<article>, , not arraylist<article>.

these 2 lines of code make absolutely no sense:

arraylist list = new arraylist<article>(); list = null; 

first of all, don't need declare list @ point. declare when need it. second, shouldn't use raw types. specify generic type of collection. third, what's point in creating new arraylist object, throw garbage bin right after reinitializing list null?

finally, exception handling awful. swallow exceptions when can meaningful solve problem. returning null rather actual result worse letting exception propagate. don't know why null, , since haven't printed exception, can't diagnose problem might be.

the way handle exception, transactions , sessions described in the hibernate documentation. session should closed in block, absolutely sure it's closed. not closing leave database connection open forever. 50 times, , application wont't able connect database anymore.


Comments