Hibernate忽略了急切的加载

时间:2016-04-16 12:50:58

标签: java hibernate lazy-loading

我的课程User包含以下字段rooms

@ManyToMany(targetEntity=Room.class, fetch=FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name="room_users",
            joinColumns={ @JoinColumn(name="user_id") },
            inverseJoinColumns={ @JoinColumn(name="room_id") })
@JsonIgnore
private List<Room> rooms = new ArrayList<>();

在某些时候,我想检查用户是否在房间里,比如

public ResponseEntity<?> joinRoom(@PathVariable Integer uid, @RequestHeader("Auth-Token") String token){
    try{
        User user = findByBackendToken(token, userRepository);
        Room room = roomRepository.findByUid(uid);

        if(user.getRooms().contains(room)){
            return new ResponseEntity<String>(HttpStatus.NOT_MODIFIED);
        } else {
            roomService.joinRoom(user, room);
        }
        return new ResponseEntity<String>(HttpStatus.OK);
    } catch(Exception e) {
        e.printStackTrace();
        return new ResponseEntity<String>(exception(e), HttpStatus.UNPROCESSABLE_ENTITY);
    }
}

但我在failed to lazily initialize a collection of role: com.inkdrop.app.domain.models.User.rooms, could not initialize proxy - no Session

行看到了user.getRooms().contains

似乎Hibernate忽略了Eager。可能有什么不对?

0 个答案:

没有答案