Why does Spring Data JPA + Hibernate generate inco

2019-09-01 22:01发布

I have two entities with a one-to-many relationship. I want to get all entities that are tied to a set of the other entity. This are my classes:

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;

}

Furthermore I have the following repository:

public interface InstanceRepository extends JpaRepository<Instance, Long> {

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

}

When I call the method with empty or single element sets, I get no errors. But if the set contains more elements I get an exception. MySQL says Operand should contain 1 column(s). The generated SQL for empty or single element sets is

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

and for other sets

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

This is obviously wrong and it should be something like

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

Why does Hibernate generate this SQL and how do I fix it?

1条回答
贼婆χ
2楼-- · 2019-09-01 22:41

According to the Spring Data spec you have to define this method as:

List<Instance> findByActionsIn(Collection<Action> actions);
查看更多
登录 后发表回答