zoukankan      html  css  js  c++  java
  • [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("
    Find 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("
    CourseView for English 101 
    " +
                        courseRepository.getCourseView(english101.getId()));
            });
  • 相关阅读:
    Asp.net调用百度搜索引擎
    iOS 之 alcatraz (插件管理器)
    @dynamic、@synthesize
    iOS 准备
    iOS 沙盒
    iOS 引导页
    iOS 开发之登陆
    iOS 程序开发
    Java 验证用户名、密码
    数据库操作
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14165033.html
Copyright © 2011-2022 走看看