0

I have a database containing a table of messages, where each message entry contains a variable for its author. I also have an ArrayList containing a list of authors. What I'd like to do is to create an SQL query that retrieves all entries from the database where the author exists in the ArrayList.

So something along these lines:

List<Message> result = session.createQuery("from Message where author ISIN ARRAYLIST order by id DESC ").list();

Anyone know how I would go about doing this?

abc32112
  • 2,457
  • 9
  • 37
  • 53

4 Answers4

4

you can set your authorlist as a named parameter:

String cmd = "from Message where author IN (:authorlist) order by id DESC";
Query q = session.createQuery(cmd);
q.setParameterList("authorlist", yourAuthorList);
List<Message> result = q.list();
chresse
  • 5,486
  • 3
  • 30
  • 47
1
ArrayList<String> authors=(ArrayList<String>)"<your list>";
String in="(";
for(String author:authors){
in +=author+",";
}
in=in.substring(0,in.length()-1);
 in +=")";
List<Message> result = session.createQuery("from Message where author IS IN "+in+" order by id DESC ").list();
user3487063
  • 3,672
  • 1
  • 17
  • 24
1

You could like this (same thing, different way):

String hql= "SELECT * FROM Message WHERE author IN ( :authors)";
Query query = session.createQuery(hql);
query.setParameterList("authors", <your authors list>);
Diogo Calazans
  • 488
  • 9
  • 18
0

String cmd = "from Message where author IN (:authorlist) order by id DESC"; Query q = session.createQuery(cmd);

q.setParameterList("authorlist", yourAuthorList); q.setParameterList("authorlist", yourAuthorList);

List<Message> result = q.list();

You can try like this but before doing like that you should aware of no of elements in ArrayList. Because it violates the query.

Please refer this link.

How to put more than 1000 values into an Oracle IN clause

Community
  • 1
  • 1
Siva Kumar
  • 1,983
  • 3
  • 14
  • 26