Select all items from a list in hibernate
I have a list of product ids and I want to get all the products from my db with a hibernate query. How can I do this?
List<Inte开发者_JS百科ger> list = custumor.getCart();
Query query = query("select product from Product product where product.id =: list");
I know this isn't the best way to solve this, but I just want to know how I can test for all the values in a list.
There are two things you'll need to do... The first is to change your HQL to the following (making use of IN), and the second is to bind your parameter list:
Query query = query("select product from Product product where product.id IN :list")
.setParameterList("list", list);
Not sure I get you but check out this link: http://www.coderanch.com/t/217864/ORM/java/Hibernate-retrieve-data-database
Specifically this snippet:
public static void retrieve() {
AnnotationConfiguration config = new AnnotationConfiguration();
config.addAnnotatedClass(User.class);
SessionFactory factory= config.configure().buildSessionFactory();
Session session = factory.getCurrentSession();
session.beginTransaction();
Query queryResult = session.createQuery("from User");
java.util.List allUsers;
allUsers = queryResult.list();
for (int i = 0; i < allUsers.size(); i++) {
User user = (User) allUsers.get(i);
}
System.out.println("Database contents delivered...");
}
Actually I just re-read your question and I see you want a sub select. You should consider using a query like:
List<Integer> list = custumor.getCart();
Query query = query("select product from Product product where product.id IN (: list)");
精彩评论