如何避免将与字段关联的对象列表检索到Hibernate实体类中?

时间:2016-12-03 17:32:42

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

我在Hibernate中绝对是新手,我对以下问题有以下疑问:

我有一个实体类映射一个表,该表包含as字段,另一个实体类映射另一个表。我想只检索与父类相关的信息,而不是与子类相关的信息。

所以我有这个 Room 实体类代表住宿的房间:

@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
}

正如您所看到的,此类包含此字段,该字段表示子实体类及其与 Room 实体类的 join 关系:

@ManyToOne
@JoinColumn(name = "id_room_tipology_fk", nullable = false)
private RoomTipology 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
}

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

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

包含与特定 RoomTipology 对象关联的会场对象列表。

然后我将这个 Spring Data JPA 存储库类与包含此查询方法的 RoomTipology 实体类相关联:

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

    @Query("from RoomTipology rt JOIN rt.rooms r WHERE r.id = :roomId")
    RoomTipology findByRoomId(@Param("roomId") Long roomId);

}

它工作正常,但我的问题是每次我称之为:

RoomTipology roomTipologyById = roomTipologyDAO.findByRoomId(7L);

返回的对象还包含与此会议室的标题相关联的会议室列表,列表会议室字段。

我的问题是,当我调用前一个 findByRoomId(@Param(“roomId”)Long roomId) DAO方法时,我只需要检索房间的尖端信息,而不是整个列表相关房间(我觉得它会很重)。

我可以避免检索与RoomTipology对象关联的房间列表吗?我该怎么办?

1 个答案:

答案 0 :(得分:0)

从另一方查询。 from Room r where r.id=?这将只加载需要的Room和相应的RoomTipology