ManyToMany 查询中的 HQL 唯一结果

发布于 2024-11-03 02:26:47 字数 851 浏览 2 评论 0原文

我有多品牌应用程序。
单个用户可以拥有多个品牌,应用程序中几乎每个查询都通过其品牌来限制用户。

用户拥有带有品牌的多对多。

例如,我想从数据库中提取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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

oО清风挽发oО 2024-11-10 02:26:47

将关键字 DISTINCT 添加到您的查询中(就在还必须添加的 SELECT 关键字之后):

s.createQuery("SELECT DISTINCT user FROM User user INNER JOIN user.brands brands WHERE brands IN(1,2)");

add the keyword DISTINCT into your query (right after the SELECT keyword that must be also added):

s.createQuery("SELECT DISTINCT user FROM User user INNER JOIN user.brands brands WHERE brands IN(1,2)");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文