【问题标题】:HQL query does not work properlyHQL 查询无法正常工作
【发布时间】:2018-01-18 14:00:06
【问题描述】:

我的 HQL 查询有一些问题:

@Query("Select s from Sport s JOIN s.categories as c where s.sportId = :sportId and c.categoryId = :categoryId")
Iterable<Sport> findByCategoryIdAndSportId(@Param("sportId")Long sportId, @Param("categoryId")Long categoryId);

此查询返回所有类别(似乎忽略了第二个 AND 子句),但仅返回与 sportId 匹配的运动。

这些是我的代表运动和类别的类:

@Entity
@Table(name = "Sports")
public class Sport  implements Serializable
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long sportId;
    @OneToMany(mappedBy = "sportId")
    @ApiModelProperty(required = true)
    @JsonManagedReference
    private Set<Category> categories;

    @Column
    private String sportName;

    ....get and set

@Entity
@Table(name = "Categories")
public class Category implements Serializable
{
    @ManyToOne
    @JoinColumn(name = "sportId", nullable = false)
    @JsonBackReference
    private Sport sportId;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long categoryId;

    ..get and set

编辑

假设:

Sport:
  |sportId | SportName  
  |1       |Rugby      
  |2       |Basket       
  |3       |Tennis 

和分类:

  |categoryId | CategoryName | sportId|
  |1          |Italy         |1       |
  |2          |England       |2       | 
  |3          |USA           |1       |
  |1          |Spain         |2       |

我想通过我的查询获得(假设 sportId=1 和 categoryId=1):

| sportId | SportName | categoryId | CategoryName |
   1         Rugby       1             Italy

有人可以帮助我吗? 提前致谢

【问题讨论】:

  • 你想从查询中得到什么结果?是否要过滤所有具有 sportId 和关联类别的运动,使其仅包含具有给定 categoryId 的类别?
  • 我假设所有类别都是指 Sport 类中的类别集合。您无法通过查询来减少此集合的内容。
  • 我用其他细节更新我的问题。
  • “看起来像”,但您似乎没有检查调用的 SQL(在日志中)。为什么不这样做,那就没有假设了?

标签: java mysql hibernate jpa hsqldb


【解决方案1】:

那是行不通的。看this

您可以反转查询以获取具有某些特定运动的类别:

Select c from Categories c JOIN Sport s where c.categoryId = :categoryId and s.sportId = :sportId

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    相关资源
    最近更新 更多