[Java Spring Data] Optional<> query response, orElse, orElseThrow, ifPresent

Repo:

public interface CourseRepository extends CrudRepository<Course,Integer>{

    Optional<Course> findByName(String name);

    @Query("Select new com.example.university.view.CourseView" +
            "(c.name, c.instructor.member.lastName, c.department.name) from Course c where c.name=?1")
    Optional<CourseView> getCourseViewByName(String name);

}

 

Test:

    @Test
    public void runtimeErrors() {

        Course course = courseRepository.findByDepartmentName("Sciences");

        //Various ways to leverage the Optional
        CourseView view = courseRepository.getCourseViewByName("English 101").get();
        view = courseRepository.getCourseViewByName("English 101").orElseThrow();
        view = courseRepository.getCourseViewByName("English 100").orElse(
                new CourseView("dummyCourse",
                        "Bad Instructor",
                        "No Department"));
    }

 

Usage:

        //*******Complex Queries********
        //Leverage Optional.ifPresent to avoid null checks
        courseRepository.findByName("English 101").ifPresent(english101 -> {
            //Select c from Course c join c.prerequisites p where p.id = ?1
            System.out.println("\nFind Courses where English 101 is a prerequisite");
            courseRepository.findCourseByPrerequisite(english101.getId())
                    .forEach(System.out::println);

            //Select new com.example.university.view.CourseView
            //  (c.name, c.instructor.member.lastName, c.department.name) from Course c where c.id=?1
            System.out.println("\nCourseView for English 101 \n" +
                    courseRepository.getCourseView(english101.getId()));
        });

 

posted @ 2020-12-20 20:40  Zhentiw  阅读(175)  评论(0编辑  收藏  举报