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()));
            });
  • 相关阅读:
    TStringList 常用操作(转自南山古陶)
    在Delphi中使用Indy控件实现邮件群发
    GSM手机SMS编码解码
    建别人进不了删不掉的文件夹
    播放 wav 文件
    delphi inherited,纯虚
    PDU编码规则
    sql函数
    基于GPRS的LED电子显示屏
    结对编程 队友代码分析
  • 原文地址:https://www.cnblogs.com/Answer1215/p/14165033.html
Copyright © 2011-2022 走看看