I need to fetch names of all students who have enrolled for the courses.
Url:-/students/{course1}/{course2} Eg /students/java/oracle
How to write controller, service and repository in rest api.
Entity:- Student Integer Id,String name and list coursenames
CodePudding user response:
What about?
@Controller
@RequestMapping("/students")
public class StudentController {
@Autowired
private StudentService studentService;
// /students/java,oracle
@GetMapping(value="/{courses}")
@ResponseBody
public String getStudents(@PathVariable String[] courses) {
return studentService.getStudents(courses);
}
}
Student
@Entity
@Table(name = "student")
public class StudentDao {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
@OneToMany(fetch = FetchType.EAGER)
@Fetch(value = FetchMode.SUBSELECT)
@JoinColumn(name = "id", referencedColumnName = "id")
private List<CourseDao> course;
}
Course
@Entity
@Table(name = "course")
public class CourseDao {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "name")
private String name;
}
In my opinion it is bad rest design. I'll create POST endpoint with body, which contains array with course Id's and find students by course id's.
CodePudding user response:
If the parameters are optional or an array you shouldn't use a path variable but use a request parameter.