Futuregeek
Futuregeek

Reputation: 1980

Retrieve multiple rows using CrudRepository

I have following result for the query select * from student where courseName = 'Science';

Results:

student_id | name   | points | course_name   | course_id |
+----------+--------+--------+---------------+-----------+
       1107| Matt   |   3000 |     Science  |    10     |
|      1108| Charley|  12348 |     Science       |    20     |

2 rows in set, 2 warnings (0.00 sec)

Java interface which implements CrudReposity :

public interface StudentDetailsRepository extends CrudRepository<StudentDetails, Long> {

  List<StudentDetails> findByCourseName(String courseName);
  List<StudentDetails> findAll();
}

Implementation :

public class StudentController {

  @Autowired
  StudentDetailsRepository studentDetailsRepository;
.............

    List<StudentDetails> studentDetails =
        studentDetailsRepository.findByCourseName(
            Request.getCourseName());
    for (int i = 0; i < studentDetails.size(); i++) {
      logger.info("entries: " + studentDetails.get(i).getName());
    }

    return request;
  }
}

In the above code, I am getting the results

entries: Matt, entries : Matt

StudentsDetails.java:

import org.springframework.data.jpa.domain.AbstractPersistable;
import javax.persistence.Entity;

@Entity(name = "com.StudentDetails")
public class StudentDetails extends AbstractPersistable<Long> {

  private long studentId;
  private String name;
  private long points;
  private String courseName;
  private long courseId;

  public StudentDetails() {

  }

  public StudentDetails(long studentId, String name, long points, String courseName, long courseId) {
    this.studentId = studentId;
    this.name = name;
    this.points = points;
    this.courseName = courseName;
    this.courseId = courseId;
  }

  public long getStudentId() {
    return studentId;
  }

  public String getName() {
    return name;
  }

  public long getPoints() {
    return points;
  }

  public String getCourseName() {
    return courseName;
  }

  public long getCourseId() {
    return courseId;
  }
}

The real problem is, it is showing size as 2 but only taking 1st row which is displaying twice. Not taking the second one. Please help me to take corresponding multiple rows from database table using CrudRepository.

Upvotes: 1

Views: 5506

Answers (1)

atul ranjan
atul ranjan

Reputation: 544

StudentsDetails.java Should have an identifier. Add @javax.persistence.Id on studentId;

@Id private long studentId;

Also List<StudentDetails> findByCourseId(String courseId); should be List<StudentDetails> findByCourseId(Long courseId);

Upvotes: 3

Related Questions