import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class StudentService {
@Autowired
private StudentRepository studentRepository;
@Autowired
private CourseRepository courseRepository;
// ✅ Create Student & Courses
public Student createStudentWithCourse(Student student) {
Set<Course> savedCourses = student.getCourses().stream()
.map(course -> courseRepository.save(course))
.collect(Collectors.toSet());
student.setCourses(savedCourses);
return studentRepository.save(student);
}
// ✅ Create Student & Assign Courses
public Student createStudent(StudentDTO studentDTO) {
Student student = new Student();
student.setName(studentDTO.getName());
Set<Course> courses = studentDTO.getCourseIds().stream()
.map(courseRepository::findById)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet());
student.setCourses(courses);
return studentRepository.save(student);
}
// ✅ Create Student Only
public Student createStudentOnly(Student student) {
return studentRepository.save(student);
}
// ✅ Get Student by ID
public Student getStudent(Long id) {
return studentRepository.findById(id).orElseThrow(() -> new RuntimeException("Student Not Found"));
}
// ✅ Add Courses to an Existing Student
public Student addCoursesToStudent(Long studentId, Set<Long> courseIds) {
Student student = studentRepository.findById(studentId).orElseThrow(() -> new RuntimeException("Student Not Found"));
Set<Course> courses = courseIds.stream()
.map(courseRepository::findById)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(Collectors.toSet());
student.getCourses().addAll(courses);
return studentRepository.save(student);
}
// ✅ Delete Student
public String deleteStudent(Long studentId) {
studentRepository.deleteById(studentId);
return "Deleted Successfully";
}
}