1. 程式人生 > 實用技巧 >[Java Spring Data] Optional<> query response, orElse, orElseThrow, ifPresent

[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()));
        });