Service Layer
The service layer provides an abstraction over the data layer. Its main purpose is to fulfill business requirements. It is always better to separate business logic from app logic.
Java
import com.example.testing_001.model.Course; import java.util.List; import org.springframework.data.domain.Page; public interface CourseService { List<Course> getAllCourses(); void saveCourse(Course course); Course getCourseById( long id); void deleteCourseById( long id); Page<Course> findPaginated( int pageNum, int pageSize, String sortField, String sortDirection); } |
The class (described below) CourseServiceImpl implements the CourseService interface and provides us with all the CRUD operations logic which is our business logic here.
Annotations used:
- @Service – This annotation is a stereotype that is used to annotate classes at service layers.
- @Autowired – This annotation is used to autowired a bean into another bean.
Java
import com.example.testing_001.model.Course; import com.example.testing_001.repository.CourseRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; @Service public class CourseServiceImpl implements CourseService{ @Autowired private CourseRepository courseRepository; @Override public List<Course> getAllCourses() { return courseRepository.findAll(); } @Override public void saveCourse(Course course) { this .courseRepository.save(course); } @Override public Course getCourseById( long id) { Optional<Course> optionalCourse = courseRepository.findById(id); Course course = null ; if (optionalCourse.isPresent()) { course = optionalCourse.get(); } else { throw new RuntimeException( "Course not found for id : " + id); } return course; } @Override public void deleteCourseById( long id) { this .courseRepository.deleteById(id); } @Override public Page<Course> findPaginated( int pageNum, int pageSize, String sortField, String sortDirection) { Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name()) ? Sort.by(sortField).ascending() : Sort.by(sortField).descending(); Pageable pageable = PageRequest.of(pageNum - 1 , pageSize, sort); return this .courseRepository.findAll(pageable); } } |
Spring MVC CRUD with Example
CRUD stands for Create, Read/Retrieve, Update, and Delete. These are the four basic operations to create any type of project. Spring MVC is a Web MVC Framework for building web applications. It is a spring module same as Spring boot, spring-security, etc. The term MVC stands for Model-View-Controller architecture. In this article, we will be building a simple course-tracking CRUD application that will be focused on the Spring MVC module.
Contact Us