Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/api/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Springboot API中带有JPA和意大利面代码的可选项_Java_Api_Hibernate_Jpa - Fatal编程技术网

Java Springboot API中带有JPA和意大利面代码的可选项

Java Springboot API中带有JPA和意大利面代码的可选项,java,api,hibernate,jpa,Java,Api,Hibernate,Jpa,我有一些关于在我正在开发的API中使用optionals的问题 首先,我在本机查询(在我的JPA存储库中)中使用返回选项。 这样使用它们没关系吧 此外,我还有一个服务,它通过id检查我的一个实体是否退出,如果不退出,它将抛出一个自定义异常。我不明白的是服务可以返回对象类型,但是JPA查询定义是:可选的findById(ID) 最后,当我想发布一个实体调用时,我有一个验证。该实体声明为: 它有两个嵌套实体,可以为空。基本的TvShowInfo和UserTvShow @Entity @Table

我有一些关于在我正在开发的API中使用optionals的问题

  • 首先,我在本机查询(在我的JPA存储库中)中使用返回选项。 这样使用它们没关系吧

  • 此外,我还有一个服务,它通过id检查我的一个实体是否退出,如果不退出,它将抛出一个自定义异常。我不明白的是服务可以返回对象类型,但是JPA查询定义是:可选的findById(ID)

  • 最后,当我想发布一个实体调用时,我有一个验证。该实体声明为:
  • 它有两个嵌套实体,可以为空。基本的TvShowInfo和UserTvShow

    @Entity
    @Table(name = "basic_tv_show_info")
    
    public class BasicTvShowInfo {
    
        @Id
        @Column(name = "id_basic_tv_show_info")
        @NotNull(message = "Provide id (Integer)")
        private Integer id;
    
        @Column(name = "original_name")
        @JsonProperty("original_name")
        @NotNull(message = "Provide original_name (String)")
        private String originalName;
    }
    
    @Entity
    @Table(name = "tv_show_created_by_user")
    public class UserTvShow {
    
        // Attributes
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "id_tv_show_created_by_user")
        private Integer idTvShowCreatedByUser;
    
        @ManyToOne()
        @JoinColumn(name= "id_user")
        @NotNull(message = "Provide user {idUser}")
        private User user;
    
        @Column(name = "name_tv_show")
        @NotNull(message = "Provide nameTvShow (String)")
        private String nameTvShow;
    
        private String genre;
    
        @Column(name = "production_company")
        private String productionCompany;
    }
    
    我在服务中有一个验证方法,用于检查:

  • 如果BasicTvShowInfo和UserTvShow都为空
  • 如果两个对象(BasicTvShowInfo和UserTvShow)都有id
  • 如果已登录的用户已具有提供的BasicTvShowInfo id的提醒
  • 如果登录的用户已经有一个带有UserTvShow id的提醒
  • 在所有这些情况下,我抛出异常

    我如何重构这个工作完美但我想写得更优雅的服务方法?我真的不喜欢使用这么多if-elseif-else和嵌套if。遵循代码变得非常困难

    方法如下:

        private void validateExistenceOfTvShowReminder(TvShowReminder tvShowReminder) throws ResourceAlreadyExistsException, BusinessLogicValidationFailure, ResourceNotFoundException {
            Optional<TvShowReminder> tvShowReminderOptional = Optional.empty();
            String messageError = null;
    
            // If both the basic tv show info object and user tv show object ARE PRESENT -> exception
            // If the basic tv show info object id already exists in the reminders table -> exception
            // If the user tv show info object id already exists in the reminders table -> exception
            // If both are null -> exception.
    
            if(tvShowReminder.getBasicTvShowInfo() != null && tvShowReminder.getUserTvShow() != null){
    
                if(tvShowReminder.getBasicTvShowInfo().getId() != null && tvShowReminder.getUserTvShow().getIdTvShowCreatedByUser() != null)
                    throw new BusinessLogicValidationFailure("You cant have a reminder that point to a tv show from the system and to a tv show created by the user");
    
            } else if(tvShowReminder.getBasicTvShowInfo() != null){
    
                if(tvShowReminder.getBasicTvShowInfo().getId() != null) {
                    tvShowReminderOptional = tvShowReminderRepository.findByUserIdAndTvShowId(tvShowReminder.getUser().getIdUser(), tvShowReminder.getBasicTvShowInfo().getId());
                    messageError = "User already created a tv show reminder with the basicTvShowInfo id : " + tvShowReminder.getBasicTvShowInfo().getId();
                }
    
            } else if (tvShowReminder.getUserTvShow() != null){
    
                if(tvShowReminder.getUserTvShow().getIdTvShowCreatedByUser() != null) {
    
                    // Validate if the user tv show of the reminder actually belongs to the logged user.
                    if(Optional.ofNullable(userTvShowService.getUserTvShow(tvShowReminder.getUser().getIdUser(), tvShowReminder.getUserTvShow().getIdTvShowCreatedByUser())).isPresent()) {
    
                        tvShowReminderOptional = tvShowReminderRepository.findByUserIdAndTvShowCreatedByUserId(tvShowReminder.getUser().getIdUser(), tvShowReminder.getUserTvShow().getIdTvShowCreatedByUser());
                        messageError = "User already created a tv show reminder with a userTvShow id : " + tvShowReminder.getUserTvShow().getIdTvShowCreatedByUser();
                    }
                }
    
            } else {
                messageError = "To create a tv show reminder you have to provided a basicTvShowInfo id OR a userTvShow id";
                throw new BusinessLogicValidationFailure(messageError);
            }
    
            // Each query findByUserIdAndTvShowId and findByUserIdAndTvShowCreatedByUserId return an optional with the tv show or an empty optional.
            // This method will return true if there is a tv show present in the optional OR returns false if is an empty optional (with null value).
            if(tvShowReminderOptional.isPresent()){
                throw new ResourceAlreadyExistsException(messageError);
            }
        }
    
    // Repository if it is of any help is:
    
    @Repository
    public interface TvShowReminderRepository extends JpaRepository<TvShowReminder, Integer> {
        Page<TvShowReminder> findByUser_IdUser(Pageable pageable, Integer idUser);
        List<TvShowReminder> findByUser_IdUser(Integer idUser);
    
        @Query(value = "SELECT * FROM tv_show_reminder WHERE id_user = ?1 and id_basic_tv_show_info = ?2", nativeQuery = true)
        Optional<TvShowReminder> findByUserIdAndTvShowId(Integer idUser, Integer idBasicTvShowInfo);
    
        @Query(value = "SELECT * FROM tv_show_reminder WHERE id_user = ?1 and id_tv_show_created_by_user = ?2", nativeQuery = true)
        Optional<TvShowReminder> findByUserIdAndTvShowCreatedByUserId(Integer idUser, Integer idTvShowCreatedByUser);
    
        @Query(value = "SELECT * FROM tv_show_reminder WHERE id_user = ?1 and id_tv_show_reminder = ?2", nativeQuery = true)
        Optional<TvShowReminder> findByIdTvShowReminderAndUserId(Integer idUser, Integer idTvShowReminder);
    }
    
    
    private void validateexistenceoftvshowlemender(tvshowlemender tvshowlemender)引发ResourceReadyExistenceException、BusinessLogicValidationFailure、ResourceNotFoundException{
    Optional tvshowmemendoroptional=Optional.empty();
    字符串messageError=null;
    //如果基本电视节目信息对象和用户电视节目对象都存在->异常
    //如果基本电视节目信息对象id已存在于提醒表->异常中
    //如果用户tv show info对象id已存在于提醒表->异常中
    //如果两者都为空->异常。
    if(TVShowEmlerance.getBasicTvShowInfo()!=null&&TVShowEmlerance.getUserTvShow()!=null){
    如果(TVShowEmlerance.getBasicTvShowInfo().getId()!=null和&TVShowEmlerance.getUserTvShow().GetIDTvShowCreatedByser()!=null)
    抛出新的BusinessLogicValidationFailure(“您不能有指向系统中的电视节目和用户创建的电视节目的提醒”);
    }else if(tvShowReminder.getBasicTvShowInfo()!=null){
    如果(tvShowReminder.getBasicTvShowInfo().getId()!=null){
    tvShowReminderOptional=tvShowReminderRepository.FindByUserandTVShowId(TVShowReminders.getUser().getIdUser(),TVShowReminders.getBasicTvShowInfo().getId());
    messageError=“用户已经创建了一个电视节目提醒,其基本id为:”+TVShowEmlerance.getBasicTvShowInfo().getId();
    }
    }else if(tvShowReminder.getUserTvShow()!=null){
    if(tvShowReminder.getUserTvShow().getIdTvShowCreatedByUser()!=null){
    //验证提醒的用户电视节目是否确实属于登录用户。
    if(可选。ofNullable(userTvShowService.getUserTvShow(tvShowReminder.getUser().getIdUser(),tvShowReminder.getUserTvShow().getIdTvShowCreatedByUser())).isPresent()){
    tvShowReminderOptional=tvShowReminderRepository.FindByUserandTVShowCreateDbyUserId(TVShowReminders.getUser().getIdUser(),TVShowReminders.getUserTvShow().getIdTvShowCreatedByUser());
    messageError=“用户已经创建了一个带有userTvShow id的电视节目提醒:”+tvShowReminder.getUserTvShow().getIdTvShowCreatedByUser();
    }
    }
    }否则{
    messageError=“要创建电视节目提醒,您必须提供基本的电视节目信息id或用户电视节目id”;
    抛出新的BusinessLogicValidationFailure(messageError);
    }
    //每个查询findByUserIdAndTvShowId和findByUserIdAndTvShowCreatedByUserId都返回一个带有电视节目的可选项或一个空的可选项。
    //如果可选项中存在电视节目,则此方法将返回true;如果可选项为空(具有null值),则此方法将返回false。
    if(TvshowRememberOptional.isPresent()){
    抛出新的ResourceReadyExistsException(messageError);
    }
    }
    //存储库(如果有任何帮助)是:
    @存储库
    公共接口TVShowMemberRepository扩展了JpaRepository{
    Page findByUser_IdUser(可分页可分页,整数IdUser);
    列出findByUser_IdUser(整数IdUser);
    @查询(value=“从电视节目提醒中选择*,其中id\u user=?1和id\u basic\u tv\u show\u info=?2”,nativeQuery=true)
    可选FindByUserandTvshowId(整数idUser、整数idBasicTvShowInfo);
    @查询(value=“从电视节目提醒中选择*,其中id\u user=?1和id\u tv\u show\u由用户创建=?2”,nativeQuery=true)
    可选FindByUserandTvShowCreatedByUserId(整数idUser,整数idTvShowCreatedByUser);
    @查询(value=“SELECT*FROM tv\u show\u rements,其中id\u user=?1和id\u tv\u show\u rements=?2”,nativeQuery=true)
    可选的findByIdTvShowReminderAndUserId(整数idUser,整数IDTvShowReminderId);
    }
    
    很抱歉发了这么长的帖子,提前谢谢你,如果有人能帮助我或指导我正确的方法,我将不胜感激

  • 首先,我在本机查询(在我的JPA存储库中)中使用返回选项。这样使用它们没关系吧
  • 我不明白为什么会不好

  • 此外,我还有一个服务,它通过id检查我的一个实体是否退出,如果不退出,它将抛出一个自定义异常。我不明白的是服务可以返回对象类型,但是JPA查询定义是:可选的findById(ID)
  • 这也很好。Spring数据只是不想在每次找不到对象时抛出异常,这就是为什么他们使用可选方法的原因。你可以用它做任何你想做的事

  • @Entity @Table(name = "basic_tv_show_info") public class BasicTvShowInfo { @Id @Column(name = "id_basic_tv_show_info") @NotNull(message = "Provide id (Integer)") private Integer id; @Column(name = "original_name") @JsonProperty("original_name") @NotNull(message = "Provide original_name (String)") private String originalName; } @Entity @Table(name = "tv_show_created_by_user") public class UserTvShow { // Attributes @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id_tv_show_created_by_user") private Integer idTvShowCreatedByUser; @ManyToOne() @JoinColumn(name= "id_user") @NotNull(message = "Provide user {idUser}") private User user; @Column(name = "name_tv_show") @NotNull(message = "Provide nameTvShow (String)") private String nameTvShow; private String genre; @Column(name = "production_company") private String productionCompany; }
        private void validateExistenceOfTvShowReminder(TvShowReminder tvShowReminder) throws ResourceAlreadyExistsException, BusinessLogicValidationFailure, ResourceNotFoundException {
            Optional<TvShowReminder> tvShowReminderOptional = Optional.empty();
            String messageError = null;
    
            // If both the basic tv show info object and user tv show object ARE PRESENT -> exception
            // If the basic tv show info object id already exists in the reminders table -> exception
            // If the user tv show info object id already exists in the reminders table -> exception
            // If both are null -> exception.
    
            if(tvShowReminder.getBasicTvShowInfo() != null && tvShowReminder.getUserTvShow() != null){
    
                if(tvShowReminder.getBasicTvShowInfo().getId() != null && tvShowReminder.getUserTvShow().getIdTvShowCreatedByUser() != null)
                    throw new BusinessLogicValidationFailure("You cant have a reminder that point to a tv show from the system and to a tv show created by the user");
    
            } else if(tvShowReminder.getBasicTvShowInfo() != null){
    
                if(tvShowReminder.getBasicTvShowInfo().getId() != null) {
                    tvShowReminderOptional = tvShowReminderRepository.findByUserIdAndTvShowId(tvShowReminder.getUser().getIdUser(), tvShowReminder.getBasicTvShowInfo().getId());
                    messageError = "User already created a tv show reminder with the basicTvShowInfo id : " + tvShowReminder.getBasicTvShowInfo().getId();
                }
    
            } else if (tvShowReminder.getUserTvShow() != null){
    
                if(tvShowReminder.getUserTvShow().getIdTvShowCreatedByUser() != null) {
    
                    // Validate if the user tv show of the reminder actually belongs to the logged user.
                    if(Optional.ofNullable(userTvShowService.getUserTvShow(tvShowReminder.getUser().getIdUser(), tvShowReminder.getUserTvShow().getIdTvShowCreatedByUser())).isPresent()) {
    
                        tvShowReminderOptional = tvShowReminderRepository.findByUserIdAndTvShowCreatedByUserId(tvShowReminder.getUser().getIdUser(), tvShowReminder.getUserTvShow().getIdTvShowCreatedByUser());
                        messageError = "User already created a tv show reminder with a userTvShow id : " + tvShowReminder.getUserTvShow().getIdTvShowCreatedByUser();
                    }
                }
    
            } else {
                messageError = "To create a tv show reminder you have to provided a basicTvShowInfo id OR a userTvShow id";
                throw new BusinessLogicValidationFailure(messageError);
            }
    
            // Each query findByUserIdAndTvShowId and findByUserIdAndTvShowCreatedByUserId return an optional with the tv show or an empty optional.
            // This method will return true if there is a tv show present in the optional OR returns false if is an empty optional (with null value).
            if(tvShowReminderOptional.isPresent()){
                throw new ResourceAlreadyExistsException(messageError);
            }
        }
    
    // Repository if it is of any help is:
    
    @Repository
    public interface TvShowReminderRepository extends JpaRepository<TvShowReminder, Integer> {
        Page<TvShowReminder> findByUser_IdUser(Pageable pageable, Integer idUser);
        List<TvShowReminder> findByUser_IdUser(Integer idUser);
    
        @Query(value = "SELECT * FROM tv_show_reminder WHERE id_user = ?1 and id_basic_tv_show_info = ?2", nativeQuery = true)
        Optional<TvShowReminder> findByUserIdAndTvShowId(Integer idUser, Integer idBasicTvShowInfo);
    
        @Query(value = "SELECT * FROM tv_show_reminder WHERE id_user = ?1 and id_tv_show_created_by_user = ?2", nativeQuery = true)
        Optional<TvShowReminder> findByUserIdAndTvShowCreatedByUserId(Integer idUser, Integer idTvShowCreatedByUser);
    
        @Query(value = "SELECT * FROM tv_show_reminder WHERE id_user = ?1 and id_tv_show_reminder = ?2", nativeQuery = true)
        Optional<TvShowReminder> findByIdTvShowReminderAndUserId(Integer idUser, Integer idTvShowReminder);
    }