【发布时间】:2016-02-05 13:44:21
【问题描述】:
在一个 spring mvc 应用程序中,我有 3 个数据库表(包括一个映射表)和它们对应的 2 个 java 实体。
实体是:-
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;
}
三个表是users、location和user_location。
我想选择一个位置 id 等于特定 id 的用户。 由于用户可以有多个位置,我不确定如何为此编写休眠查询。我在下面尝试了几种组合,但要么遇到异常,
illegal attempt to dereference collection [{synthetic-alias}{non-qualified-property-ref}] with element property reference [id]
或获取用户和位置对象的列表。我只想要一个用户对象列表。
- 来自用户 where userName = :userName and :locationId in (location.id)
- 从用户用户内部加入 user.location loc where user.userName = :usersName and loc.id = :locationId
更新: 我试过查询,
Query query = getCurrentSession().createQuery("from User user inner join user.location loc where user.userName = :usersName and loc.id = :locationId");
Hibernate 从上述查询生成以下普通 SQL 并返回用户和位置对象列表。例如,如果用户的一个位置与上述查询相匹配,则休眠返回一个包含一个用户和一个位置对象的列表。
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,请查看我的更新以响应您的评论。谢谢
标签: mysql spring hibernate spring-mvc