gpt4 book ai didi

java - Hibernate 对父类的查询会创建无效的联合查询

转载 作者:行者123 更新时间:2023-12-02 10:32:56 25 4
gpt4 key购买 nike

我正在使用 spring boot 和 hibernate,并且我有以下数据结构。

@Entity
public class Template {

@Id
private Integer id;

@OneToMany(mappedBy = "template", orphanRemoval = true, fetch = FetchType.EAGER,cascade = CascadeType.ALL)
@BatchSize(size = 30)
private Collection<TemplateContent> contents;
}

@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class TemplateContent {

@Id
private String contentType;

@Id
@ManyToOne(fetch = FetchType.EAGER, optional = false)
@JoinColumn(name = "template_id", nullable = false)
private Template template;
}

@Entity
public class SomeContent extends TemplateContent {

private String someValue;
}

@Entity
public class SomeOtherContent extends TemplateContent {

private String someOtherValue;
}

@Repository
public interface TemplateRepository extends JpaRepository<Template, Integer> {
Page<Template> findByIdIn(Collection<Integer> ids, Pageable pageable);
}

当我调用 findByIdIn 方法时,它会生成以下查询:

SELECT ...
FROM (SELECT content_type,
template_id,
some_value,
NULL AS some_other_value
FROM someContent
UNION
SELECT content_type,
template_id,
some_other_value,
NULL AS some_value
FROM someOtherContent) contents0_
WHERE contents0_.template_id IN ( ?, ?, ? )

这是无效的,因为 MySQL 无法在派生表上使用索引。有没有办法生成更有效的查询。

//this would be the desired query
SELECT ...
FROM (SELECT content_type,
template_id,
some_value,
NULL AS some_other_value
FROM someContent
WHERE template_id IN ( ?, ?, ? )
UNION
SELECT content_type,
template_id,
some_other_value,
NULL AS some_value
FROM someOtherContent
WHERE template_id IN ( ?, ?, ? )) contents_0_ ....

我也尝试过使用不同的继承策略,但似乎它们都有类似的缺点。

最佳答案

如果您想在多态查询中获得最佳性能,最好的方法是使用strategy = InheritanceType.SINGLE_TABLE,可能您会为空列付出性能代价,但这取决于哪个方面对你,还因为 strategy = InheritanceType.JOINED 也有 TABLE_PER_CLASS

的相同问题

关于java - Hibernate 对父类的查询会创建无效的联合查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53501100/

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