简体   繁体   English

使用JPA(条件搜索)在springboot中根据ID以外的其他字段查找表中的所有记录

[英]Find all records in a table based on other field than ID in springboot using JPA(Conditional Search)

I am new to spring boot and making a question answer system.我是 Spring Boot 的新手,正在制作问答系统。 I want to find all questions based on their course id (Which is not a primary key).我想根据他们的课程 ID(不是主键)找到所有问题。 I am getting an error as: " query did not return a unique result: 2; nested exception is javax.persistence.NonUniqueResultException: query did not return a unique result: 2 ".我收到如下错误:“查询未返回唯一结果:2;嵌套异常为 javax.persistence.NonUniqueResultException:查询未返回唯一结果:2 ”。 I am This is my work as of now.我是这是我现在的工作。

Bean Class:豆类:

@Entity
@Table(name = "questions")
public class Question {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name="question_id")
    private int question_id;

    @Column(name="question")
    private String question;

    @Column(name="course_id")
    private int courseId;

    //getters and setters
}

Repository:存储库:

@Repository("questionRepository")
public interface QuestionRepository extends CrudRepository<Question, Integer>{
    Question findAllByCourseId(int courseId);
}

Service:服务:

public interface QuestionService {
    Question save(Question question);
    List<Question> listAllQuestion();
    Question findByQuestionName(String questionName);
    List<Question> findAllByCourseId(int courseId);
}

Service Implementation:服务实施:

public List<Question> findAllByCourseId(int courseId) {
    return (List<Question>) questionsRepository.findAllByCourseId(courseId);
}

I know the code is imperfect in many ways as i am beginner.我知道代码在很多方面都不完美,因为我是初学者。 I want some suggestions too for improvement.我也想要一些改进的建议。 Thank you.谢谢你。

您应该将您的存储库查找更改为列表,因为您有多个具有相同课程 ID 的问题。

List<Question> findAllByCourseId(int courseId);

As courseId is not primary key so course contains many courses belong to one CourseId.由于 courseId 不是主键,因此 course 包含许多属于一个 CourseId 的课程。

So make sure if you are retrieving many records then use List as a return type.因此,请确保您正在检索许多记录,然后使用 List 作为返回类型。

1) In your questionRepository.Make below change. 1) 在您的 questionRepository.Make 下面更改。

List<Question> findAllByCourseId(int courseId);

0 0

No, you don't need to make criteria query it would be boilerplate code you just do simple thing if you working in Spring-boot: in your repo declare a method name with findBy[exact field name] .不,您不需要进行条件查询,这将是样板代码,如果您在 Spring-boot 中工作,您只需做简单的事情:在您的存储库中使用findBy[exact field name]声明一个方法名称。 Example- if your model or document consist a string field myField and you want to find by it then your method name will be:示例 - 如果您的模型或文档包含一个字符串字段myField并且您想通过它查找,那么您的方法名称将是:

findBymyField(String myField); findBymyField(String myField);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM