본문 바로가기

🌱JAVA/시나리오 개발

Insert 시 PK 값을 자동으로 늘려주는 API

# 특정 값을 Insert 시 PK 값을 자동으로 늘리면서 Insert 하는 API

# Controller

    /**
     * 시나리오
     * 1. 만약 user_table 의 userid=1, username 이 김승현 인 경우
     * 2. userid값이 하나씩 증가하며 입력한 내용을 Insert하는 API이다.
     */
    @PostMapping("/apply_some_data_save")
    public GeneralResponse<?> apply_some_data_save(@RequestParam(value = "userid") Long userid,
                                                   @RequestParam(value = "published") Boolean published,
                                                   @RequestParam(value = "user_description") String user_description,
                                                   @RequestParam(value = "username") String username) {

        return userService.apply_some_data_save(userid, published, user_description, username);
    }

# Service

    public GeneralResponse<?> apply_some_data_save(Long userid, Boolean published, String user_description, String username) {
        String optionalUserEntity = userRepository.apply_some_data_save_select(userid, username);
        if (optionalUserEntity.isEmpty()) {
            return GeneralResponse.builder()
                    .status(false)
                    .message("not found")
                    .data(null)
                    .build();
        }
        int user_id_plus = userRepository.user_id_plus1();
        int user_id_plus1 = user_id_plus + 1;
        int optionalUserEntityInsert = userRepository.apply_some_data_insert_rows(user_id_plus1, published, user_description, username);
        System.out.println("스트링 값 조회: " + optionalUserEntityInsert);
        return GeneralResponse.builder()
                .status(true)
                .message("get user_list")
                .dataString(optionalUserEntityInsert)
                .data(optionalUserEntityInsert)
                .build();
    }

# Repository

    @Transactional
    @Query(value = "select userid, username from user_table where userid = :userid and username = :username", nativeQuery = true)
    String apply_some_data_save_select(@Param("userid") Long userid,
                                       @Param("username") String username);

    @Transactional
    @Query(value = "select userid from user_table ORDER by userid DESC limit 1", nativeQuery = true)
    int user_id_plus1();

    @Transactional
    @Modifying
    @Query(value = "insert into user_table " +
            "(userid, published, user_description, username) " +
            "VALUES(:user_id_plus1, :published, :user_description, :username)", nativeQuery = true)
    int apply_some_data_insert_rows(@Param("user_id_plus1") int user_id_plus1,
                                    @Param("published") Boolean published,
                                    @Param("user_description") String user_description,
                                    @Param("username") String username);

- 끝 -