lunes, 19 de marzo de 2018

SpringBoot Road 2

Spring Boot desde Eclipse con REST

En github https://github.com/jalbertomr/SpringBootQuickStartEclipse.git

@Entity
public class Course {

@Id
private String id;
private String name;
private String description;
@ManyToOne
private Topic topic;

public Course() {
}

public Course(String id, String name, String description, String topicId) {
super();
this.id = id;
this.name = name;
this.description = description;
this.topic = new Topic(topicId, "", "");
}

getters y setters...
------------
public interface CourseRepository extends CrudRepository<Course, String> {

public List<Course> findByTopicId(String topicId);

//No se tiene que decralar el metodo, con el nombre formateado como findByProperty
//Spring Data JPA implementara el metodo automaticamente
//ejemplo
//public List<Course> findByName(String name);
//public List<Course> findByDescription(String foo);
}
-------------
@Service
public class CourseService {
@Autowired
private CourseRepository courseRepository;
public List<Course> getAllCourses(String topicId) {
List<Course> courses = new ArrayList<Course>();
courseRepository.findByTopicId(topicId)
.forEach(courses::add);
return courses;
}
public Course getCourse(String id) {
return courseRepository.findById(id).get();
}

public void addCourse(Course course) {
courseRepository.save(course);
}

public void updateCourse(String id, Course course) {
courseRepository.save(course);
}

public void deleteCourse(String id) {
courseRepository.deleteById(id);
}
}
----------------
@RestController
public class CourseController {
@Autowired
private CourseService courseService;
    @RequestMapping("/temas/{temasId}/cursos")
public List<Course> getAllCourses(@PathVariable String temasId) {
return courseService.getAllCourses(temasId);
}
    
    @RequestMapping("/temas/{temaid}/cursos/{id}")
    public Course getCourse(@PathVariable String id) {
    return courseService.getCourse(id);
    }
    
    @RequestMapping(method=RequestMethod.POST, value="/temas/{temasId}/cursos")
    public void addCourse(@RequestBody Course course, @PathVariable String temasId) {
    course.setTopic(new Topic(temasId, "", ""));
    courseService.addCourse(course);
    }
    
    @RequestMapping(method=RequestMethod.PUT, value="/temas/{temasId}/cursos/{id}")
    public void updateCourse(@RequestBody Course course, @PathVariable String id, @PathVariable String temasId ) {
    course.setTopic(new Topic(temasId, "", ""));
    courseService.updateCourse(id, course);
    }
    
    @RequestMapping(method=RequestMethod.DELETE, value="/temas/{temasId}/cursos/{id}")
    public void deleteCourse(@PathVariable String id) {
    courseService.deleteCourse(id);
    }
}



fdt

No hay comentarios:

Publicar un comentario