Be.younick
Be.younick

Reputation: 17

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.

Upvotes: 0

Views: 5725

Answers (2)

Angad Bansode
Angad Bansode

Reputation: 923

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);

Upvotes: 1

abdul
abdul

Reputation: 1581

You should change your repository find to list, because you have multiple questions with the same course id.

List<Question> findAllByCourseId(int courseId);

Upvotes: 3

Related Questions