gpt4 book ai didi

java - Hibernate - 通过仅知道类的 ID 返回实体集合

转载 作者:行者123 更新时间:2023-11-30 07:36:54 26 4
gpt4 key购买 nike

我如何加载给定类的实体集合,只需访问数据库一次,例如:

 public Collection<Object> getEntities(Class<?> entityClass,Collection<Serializable> listOfIDs);

我知道如果我只想获取单个实体,我可以使用:

sessionFactory.getCurrentSession().get(Class,Serializable);

但似乎没有可序列化集合的匹配选项。

请注意,由于我只知道类,我不知道身份列的名称,因此在没有首先发现 ID 列的情况下,简单的 HQL/Criteria API 不是一个选项。

最佳答案

Hibernate 不提供开箱即用的支持。但是您可以借助特殊的 id 属性在 HQL 中实现这一点:

14.5. Referring to identifier property

There are 2 ways to refer to an entity's identifier property:

  • The special property (lowercase) id may be used to reference the identifier property of an entity provided that the entity does not define a non-identifier property named id.
  • If the entity defines a named identifier property, you can use that property name.

所以你可以这样做:

Query q = session.createQuery("from " + clazz.getName() + " where id IN :idList")

关于java - Hibernate - 通过仅知道类的 ID 返回实体集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3110537/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com