在春天的mvc應用程序中,我有3個數據庫表(包括一個映射表)及其2個對應的java實體。選擇記錄其中id是集合ID之一
的實體是: -
public class User {
private Long id;
private String userName;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "user_location",
joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "location_id", referencedColumnName = "id")}
)
private Set<Location> location;
}
public class Location {
private Long id;
private String locationCode;
}
三表是用戶,位置和USER_LOCATION。
我想選擇一個用戶的位置ID等於一個特定的ID。 由於用戶可以有多個位置,我不知道如何爲此編寫一個hibernate查詢。我嘗試了以下幾種組合,但我要麼得到一個例外,
illegal attempt to dereference collection [{synthetic-alias}{non-qualified-property-ref}] with element property reference [id]
或獲取用戶和位置對象的列表。我只想要一個用戶對象列表。
- 從用戶其中username =:userName和:locationId在(location.id)
- 從用戶用戶內部聯接user.location LOC其中user.userName =:usersName和loc.id =:locationId
更新: 我嘗試查詢,
Query query = getCurrentSession().createQuery("from User user inner join user.location loc where user.userName = :usersName and loc.id = :locationId");
休眠產生以下從上方滑動SQL查詢並返回用戶和位置對象的列表。例如,如果有一個用戶匹配上面的查詢位置,hibernate會返回一個包含一個用戶和一個位置對象的列表。
select
user0_.id as id1_18_0_,
location2_.id as id1_5_1_,
user0_.user_name as user_na11_18_0_,
location2_.location_code as location3_5_1_
from
users user0_
inner join
user_location location1_
on user0_.id=location1_.user_id
inner join
location location2_
on location1_.location_id=location2_.id
where
user0_.user_name=?
and location2_.id=?
你說的用戶和定位對象的名單是什麼意思?你可以添加你的查詢到帖子? –
您好,Orest,請參閱我的更新以迴應您的評論。謝謝 – ivish