如何才能正确实现涉及两个表之间的JOIN的Spring Data JPA命名查询?

时间:2016-11-29 21:42:24

标签: java spring hibernate jpa spring-data-jpa

我正在使用 Spring Data JPA 开发Spring应用程序。我实现了命名查询方法来实现我的查询。我在尝试实现涉及2个表\实体类之间的连接的命名查询时遇到了一些困难。

所以我有这两个实体类:

1)房间代表住宿的房间:

@Entity
@Table(name = "room")
public class Room implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @ManyToOne
    @JoinColumn(name = "id_accomodation_fk", nullable = false)
    private Accomodation accomodation;

    @ManyToOne
    @JoinColumn(name = "id_room_tipology_fk", nullable = false)
    private RoomTipology roomTipology;

    @Column(name = "room_number")
    private String number;

    @Column(name = "room_name")
    private String name;

    @Column(name = "room_description")
    @Type(type="text")
    private String description;

    @Column(name = "max_people")
    private Integer maxPeople;

    @Column(name = "is_enabled")
    private Boolean isEnabled;

    // CONSTRUCTOR, GETTER AND SETTER METHODS
}

如您所见,此类包含此字段:

@ManyToOne
@JoinColumn(name = "id_room_tipology_fk", nullable = false)
private RoomTipology roomTipology;

将许多Room实例链接到RoomTipology实例。

2)然后我有 RoomTipology 实体类:

@Entity
@Table(name = "room_tipology")
public class RoomTipology implements Serializable{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "tipology_name")
    private String name;

    @Column(name = "tipology_description")
    private String description;

    @Column(name = "time_stamp")
    private Date timeStamp;

    @OneToMany(mappedBy = "roomTipology")
    private List<Room> rooms;

    @OneToOne(mappedBy = "roomTipology")
    private RoomRate roomRate;

    // CONSTRUCTOR, GETTER AND SETTER METHODS
}

然后我有 RoomTipology 实体类的这个存储库clas,类似于:

@Repository
@Transactional(propagation = Propagation.MANDATORY)
public interface RoomTipologyDAO extends JpaRepository<RoomTipology, Long> {

    RoomTipology findByRoomTipology_Room(Room room);

}

我尝试过这种方式,但它无法正常工作,我收到以下错误消息:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'roomTipologyDAO': Invocation of init method failed; nested exception is org.springframework.data.mapping.PropertyReferenceException: No property roomTipology found for type RoomTipology!

我想从会议室开始检索相关的 RoomTipology 实例。基本上我想将此SQL查询转换为Spring Data JPA命名查询:

SELECT * 
FROM `room_tipology` rt 
INNER JOIN room r
ON rt.id = r.id_room_tipology_fk
WHERE r.id = 7

其中r.id是 Room 实体的id字段的值。

我知道如果我已经拥有 Room 对象,我可以获取此信息:

room.getRoomTipology()

但有时我只是拥有 Room 实例的ID,我想直接检索相关的 RoomTipology 对象。

如何使用命名查询来完成?

1 个答案:

答案 0 :(得分:0)

以您认为最佳方式命名您的方法,传递roomId而不是房间,因为这是您的实际搜索参数,并使用

注释方法
@Query("select t from Room r join r.roomTypology t where r = :roomId")