简体   繁体   中英

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. I want to find all questions based on their course id (Which is not a primary key). 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 ". 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.

So make sure if you are retrieving many records then use List as a return type.

1) In your questionRepository.Make below change.

List<Question> findAllByCourseId(int courseId);

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] . Example- if your model or document consist a string field myField and you want to find by it then your method name will be:

findBymyField(String myField);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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