Need help on Hibernate and JPQL syntax
I am new to play framework and hibernate , I have a simple problem that I am unable to solve
public static void listMembers(int page,int pageSize,String[] fields,String[] values) {
List<Member> members = Member.find(query,params).fetch();
render(members);
}
I am unsure how to write the query and the params
as I want each field to be checked against corresponding valuesomething like this ( which generates errors) :
public static void listMembers(int page,int pageSize,String[] fields,String[] values) {
String query = "" ;
String[] params = new String[values.length*2] ;
int i = 0 ;
for(i = 0 ; i < fields.length-1 ; i+=2 ) {
query += "?"+(i+1)+" like ?"+(i+2)+" AND" ;
params[i] = fields[i] ;
params[i+1] = "%"+values[i]+"%" ;
}
query += "?"+(i+1)+" like ?"+(i+2) ;
params[i] = fields[i] ;
params[i+1] = values[i] ;
List<Member> members = Member.find(query,params).fetch();
render(members);
}
Edit: Such that the query will be :
?1 like ?2 AND ?3 like ?4 AND .....
and param开发者_Go百科s will be:
field1,%value1%,field2,%value2%,...
I think it's better to use setParameter() and EntityManager:
String jpql = "select m from Member m where ";
for (int i = 0; i < fields.length; i++) {
jpql += (i > 0 ? " AND " : "") + fields[i] + " like '%?%' ";
}
Query q = entityManager.createQuery(jpql);
for (int i = 1; i <= values; i++) {
q.setParameter(i, values[i]);
}
List<Members> members = q.getResultList();
精彩评论