【问题标题】:Hibernate single query for common table across children?跨孩子的公共表的休眠单个查询?
【发布时间】:2013-12-12 02:39:07
【问题描述】:

我希望让 hibernate 对当前正在执行多个查询的事物执行单个查询。我的场景是使用 JPA/hibernate 注释定义的父对象:

@javax.persistence.Entity
@Table(name="example")
@Inheritance(strategy=InheritanceType.JOINED)
public class Example implements Serializable {
...
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER, mappedBy = "theId")
@LazyCollection(LazyCollectionOption.FALSE)
@BatchSize(size=1000)
private Set<ChildObjectOne> childrenOne = new LinkedHashSet<>();

@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER, mappedBy = "theId")
@LazyCollection(LazyCollectionOption.FALSE)
@BatchSize(size=1000)
private Set<ChildObjectTwo> childrenTwo = new LinkedHashSet<>();

@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER, mappedBy = "theId")
@LazyCollection(LazyCollectionOption.FALSE)
@BatchSize(size=1000)
@MapKeyColumn(name="attribute_id")
private Map<String, TheAttribute> attributes = new HashMap<>();

一对多映射中的每个类(本例中为 ChildObjectOne 和 ChildObjectTwo)的属性映射与上述示例类中映射的属性完全相同

Attribute 类的定义如下

@javax.persistence.Entity
@IdClass(TheAttributePK.class)
@Table(name="the_attribute")
public class TheAttribute implements Serializable {

@Id
@Column(name = "the_id", nullable = false)
private long theId;
@Id
@Column(name = "attribute_id", length = 255, nullable = false)
private String attributeId;
...

我一直在尝试做的是让 hibernate 对任何特定 Example 实例的所有子对象的所有属性执行单个查询,而不是为实体的每个子对象执行查询。这在一次批量加载多个示例实例时尤其有用:

@Query("SELECT e FROM Example e where e.theId in (:ids)")
List<Example> findAllByExampleIds(@Param("ids") List<Long> ids);

有没有办法使用 jpa 或 hibernate 注释通过 hibernate 获得这种所需的行为?

【问题讨论】:

    标签: hibernate


    【解决方案1】:

    请看这里的问题

    FetchMode join makes no difference for ManyToMany relations in spring JPA repositories

    您可以在 hql 查询中使用 join fetch 来实现这一点。

    【讨论】:

    • 性能是这种方法的一个问题。昨晚我只为孩子们尝试了它(我无法让孩子们的孩子们工作),发现批量大小的方法降低了性能。 mysql 的解释显示了一个“使用临时”,可以解释它 - 我们有一些非常大的表 - 例如属性表是 7.11 亿行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-04
    • 1970-01-01
    相关资源
    最近更新 更多