为什么 Spring Data JPA + Hibernate 生成不正确的 SQL?

Why does Spring Data JPA + Hibernate generate incorrect SQL?

我有两个具有一对多关系的实体。我想获得所有实体 与一组其他实体相关联。这是我的 类:

public class Instance {

    @Id
    @GeneratedValue
    private long id;

    @OneToMany(mappedBy = "instance")
    private Set<Action> actions = new HashSet<>();

}

public class Action {

    @Id
    @GeneratedValue
    private long id;

    @ManyToOne
    @JoinColumn(name = "instance_id")
    private Instance instance;

}

此外,我有以下存储库:

public interface InstanceRepository extends JpaRepository<Instance, Long> {

    List<Instance> findByActions(Set<Action> actions);

}

当我使用空元素集或单个元素集调用方法时,我没有收到任何错误。但是如果集合包含更多元素 我得到一个例外。 MySQL 表示 Operand should contain 1 column(s)。为空或单个元素生成的 SQL 集合是

select instance0_.id as id1_3_
from instance instance0_
left outer join action actions1_
on instance0_.id=actions1_.instance_id
where actions1_.id=?

以及其他集合

select instance0_.id as id1_3_
from instance instance0_
left outer join action actions1_
on instance0_.id=actions1_.instance_id
where actions1_.id=(?, ?, ?, ...)

这显然是错误的,应该是这样的

select instance0_.id as id1_3_
from instance instance0_
left outer join action actions1_
on instance0_.id=actions1_.instance_id
where actions1_.id in (?, ?, ?, ...)

为什么 Hibernate 会生成这个 SQL 我该如何解决它?

根据 Spring 数据 spec 您必须将此方法定义为:

List<Instance> findByActionsIn(Collection<Action> actions);