java 从休眠中的列表中选择所有项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6360931/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:34:04  来源:igfitidea点击:

Select all items from a list in hibernate

javasqldatabasehibernate

提问by fibera

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?

我有一个产品 ID 列表,我想通过休眠查询从我的数据库中获取所有产品。我怎样才能做到这一点?

List<Integer> 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.

我知道这不是解决此问题的最佳方法,但我只想知道如何测试列表中的所有值。

回答by stevevls

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:

您需要做两件事......第一件事是将您的 HQL 更改为以下内容(使用 IN),第二件事是绑定您的参数列表:

Query query = query("select product from Product product where product.id IN :list")
    .setParameterList("list", list);

回答by Mark D

Not sure I get you but check out this link: http://www.coderanch.com/t/217864/ORM/java/Hibernate-retrieve-data-database

不确定我是否理解您,但请查看此链接: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)");