HQL查询无法正常工作

时间:2018-01-18 14:00:07

标签: java mysql hibernate jpa hsqldb

我在使用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
有人可以帮帮我吗? 提前致谢

1 个答案:

答案 0 :(得分:0)

那不行。请看this

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

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