Spring JPA Repository返回相同对象的列表

时间:2018-03-08 17:29:51

标签: mysql spring-data-jpa

我有一个Spring JPA Repository,它以奇怪的方式运行。确切地说,它返回一个对象列表,这些对象看起来都是相同的,尽管底层数据库查询似乎返回了正确的信息。

实体类如下。它对应于MySQL中的视图。

@Entity
@Getter
@Cacheable(false)
@Table(name="view_assignment_selector")
public class AssignmentSelectorView {

    @EmbeddedId private ID id;
    private int areaId;
    private String name;
    @Enumerated(EnumType.ORDINAL) private Preference preference;
    private int assigned;
    private int required;
    private boolean selected;


    @Embeddable @Getter
    public static class ID implements Serializable {
        private Integer volunteerId;
        private Integer sessionId;
    }

}

这是存储库:

public interface AssignmentSelectorViewRepository extends JpaRepository<AssignmentSelectorView, AssignmentSelectorView.ID> {
    List<AssignmentSelectorView> findByIdVolunteerIdAndIdSessionId(int volunteerId, int sessionId);
}

以下是MySQL记录的生成查询:

SELECT AREAID, ASSIGNED, NAME, PREFERENCE, REQUIRED, SELECTED, SESSIONID, VOLUNTEERID FROM view_assignment_selector WHERE ((VOLUNTEERID = 820) AND (SESSIONID = 32))

当我直接在MySQL中尝试查询时,结果是正确的。但AssignmentSelectorView对象列表的大小正确,但所有条目都与第一个相同。

这里发生了什么?

1 个答案:

答案 0 :(得分:0)

经验教训 - 特别注意Ids。 为Views编写@Entity类非常棘手,因为Views实际上没有主键,但@Entity类仍需要Id。

我原来的ID错误,因为2列不是唯一的。我需要第3列。正确的ID是:

@Embeddable @Getter
public static class ID implements Serializable {
    private Integer volunteerId;
    private Integer sessionId;
    private Integer areaId;
}

现在可行。