使用CrudRepository检索多行

时间:2017-08-16 18:46:59

标签: java spring hibernate rest

我对查询select * from student where courseName = 'Science';

有以下结果

结果:

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)

实现CrudReposity的Java接口:

public interface StudentDetailsRepository extends CrudRepository<StudentDetails, Long> {

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

实施:

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

在上面的代码中,我得到了结果

  

条目:Matt,条目: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;
  }
}

真正的问题是,它显示的是2的大小,但只显示了显示两次的第1行。没有采取第二个。请帮我用CrudRepository从数据库表中获取相应的多行。

1 个答案:

答案 0 :(得分:3)

StudentsDetails.java应该有一个标识符。 在studentId上添加@ javax.persistence.Id;

@Id private long studentId;

另外 List<StudentDetails> findByCourseId(String courseId);  应该    List<StudentDetails> findByCourseId(Long courseId);

相关问题