ManyToMany 查询中的 HQL 唯一结果
我有多品牌应用程序。
单个用户可以拥有多个品牌,应用程序中几乎每个查询都通过其品牌来限制用户。
用户拥有带有品牌的多对多。
例如,我想从数据库中提取List
。
s.createQuery("FROM User user INNER JOIN user.brands brands WHERE brands IN(1,2)");//(1,2) = :brands
在这种情况下,我将多次获得同一用户,因为该用户有多个品牌与其关联。
如何在不需要明确的情况下查询品牌而不影响我的结果?
这是用户实体:
public class User {
@Id
@Column(name="USER_ID")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer userId;
@ManyToMany(fetch=FetchType.EAGER)
@JoinTable(name="USERS_BRANDS" , joinColumns = {@JoinColumn(name="USER_ID")},inverseJoinColumns={@JoinColumn(name="BRAND_ID")})
private Collection<Brand> brands;
...other members
...getters and setters
}
谢谢
I have multi branded application.
single user can have more than one brands, almost every query in the application restrict the user by its brands.
User has ManyToMany with Brand(s) .
For example, I want to pull List<Employee>
from the DB.
s.createQuery("FROM User user INNER JOIN user.brands brands WHERE brands IN(1,2)");//(1,2) = :brands
In this situation I will get the same user more than once because the User has more than one brand connected to him.
How can query the Brand without letting effect of my results without the need of distinct?
This is the User Entity:
public class User {
@Id
@Column(name="USER_ID")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer userId;
@ManyToMany(fetch=FetchType.EAGER)
@JoinTable(name="USERS_BRANDS" , joinColumns = {@JoinColumn(name="USER_ID")},inverseJoinColumns={@JoinColumn(name="BRAND_ID")})
private Collection<Brand> brands;
...other members
...getters and setters
}
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将关键字 DISTINCT 添加到您的查询中(就在还必须添加的 SELECT 关键字之后):
add the keyword DISTINCT into your query (right after the SELECT keyword that must be also added):