Spring Data JPA加入了两个或更多的entites

时间:2016-02-26 10:31:52

标签: mysql spring-data spring-data-jpa

我有三个实体,

@Entity
public class Deck {

    @Id
    private int id;
    private int number;
    private String name;

    @OneToMany(mappedBy = "deck")
    private Set<Lab> labs;

    //getter and setter methods

}

@Entity
public class Lab {

    @Id
    private int id;
    private String name;

    @ManyToOne
    private Deck deck;

    @OneToMany(mappedBy = "lab")
    private Set<LabBooking> labBooking;

    //getter and setter methods

}

@Entity
public class LabBooking {

    @Id
    private int id;

    private Date startTime;
    private Date endTime;

    @ManyToOne
    private Lab lab;

    //getter and setter methods

}

以下是LabRepository,

public interface LabRepository extends CrudRepository<Lab, Integer>{

    @Query("SELECT l FROM Lab l JOIN l.labBooking lb WHERE l.deck.id = :deckId AND lb.startTime > '2016-02-24 15:00:00'")
    List<Lab> findLabs(@Param("deckId") int deckId);

}

我正在尝试检索特定时间内占用的卡组中的实验室列表。

当我在MySQL中执行等效查询(SELECT * FROM lab l JOIN lab_book lb ON l.id = lb.lab_id WHERE l.deck_id = 9999 AND lb.start_time > '2016-02-24 15:00:00')时,我得到以下结果

id      name    deck_id id  end_time            start_time          lab_id
9001    Lab One 9999    5   2016-02-24 17:00:00 2016-02-24 16:00:00 9001

在spring应用程序中,我得到以下结果,

[{
    "lab_id": 9001,
    "lab_name": "Lab One",
    "lab_booking": [{
        "id": 4,
        "start_time": "2016-02-24 15:00:00",
        "end_time": "2016-02-24 16:00:00"
    }, {
        "id": 5,
        "start_time": "2016-02-24 16:00:00",
        "end_time": "2016-02-24 17:00:00"
    }, {
        "id": 3,
        "start_time": "2016-02-24 14:00:00",
        "end_time": "2016-02-23 14:30:00"
    }]
}]

Lab对象应该只包含预订ID 5,而是显示所有ID。

如果sql查询返回5条记录,则存储库返回5个重复的Lab对象。可能是什么问题?

1 个答案:

答案 0 :(得分:0)

似乎你失踪了。

SELECT distinct l FROM Lab l JOIN l.labBooking lb WHERE l.deck.id = :deckId AND lb.startTime > '2016-02-24 15:00:00'"