【问题标题】:QueryException: could not resolve property: catId of: com.my.myquiz.entity.QuestionQueryException:无法解析属性:catId of:com.my.myquiz.entity.Question
【发布时间】:2019-02-04 15:09:41
【问题描述】:

我使用 Spring 数据创建了简单的测验,并使用注释将问题和类别映射到 多对一 关系中。我很想在给定的类别下获得随机问题,但它给出了上述错误,我尝试了几个替代方案。但似乎不起作用。

Category.java

@Entity
@Table(name = "categories")
public class Category {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long catId;

    @Column(nullable = false , unique = true)
    private String description;

Question.java

@Entity
@Table(name = "question")
public class Question {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long questionId;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "catId", nullable = false, updatable = false)
    @JsonBackReference
    private Category category;

    @Lob
    @Column (nullable = false)
    private String question;

    @Column (nullable = false)
    private String medium;

QuestionRepository.java

@Repository
@Transactional
public interface QuestionRepository extends JpaRepository<Question, Long> {

    @Query("select question from Question question where question.catId = :catId AND question.medium = :medium order by function('RAND')")
    List<Question> getQuestionsForAttempt(@Param("catId") Long catId , @Param("medium") String medium);

    @Query("select question from Question  question where question.catId = : catId")
    List<Question> getQuestionByCategory(@Param("catId") Long catId);
}

【问题讨论】:

    标签: spring-boot jpa spring-data-jpa many-to-one


    【解决方案1】:

    这是 JPQL 而不是 SQL,因此您必须考虑查询中的依赖关系:

    select question from Question  question where question.category.catId
    

    select question from Question  question  inner join question.category c where c.catId
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-25
      • 2014-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多