0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【ユーザーIDに一致してるデータのみをJPQLを使って取得する方法】

Posted at

今回はユーザー情報の編集機能を作ろうと思い、ユーザー情報の一覧取得→表示ということをしたいです。
ログインする際に、POSTしたユーザーidを保持して、それをGETリクエストで送って表示するという流れです。

まず現在のユーザーコントローラークラスはこんな感じです。ただ単にデータベースにあるすべての情報を取ってくるという感じになってます。

 @GetMapping("/users")
        public List<Users>getUsers() {
        return usersService.getUsers();
    }

それをこんな感じに変えました。
@RequestParamを使うことによってフロントから送られてきたログイン中のユーザーidを受け取ることができます。

 @GetMapping("/users") //@RequestParamブラウザからのリクエストの値(パラメータ)を取得することができるアノテーション) 
        public List<UsersListDto>getUsers(@RequestParam Integer id){
        return usersService.getUsers(id);
        

こちらが現在のサービスクラスです。
findAllのメソッドを使ってとりあえず全部返すだけになってます。

public List<Users> getUsers() {
         return usersRepository.findAll();
        //getUsersは、スレッドリポジトリのfindUserの中身を返す
    }

それがこんな感じになりました。
コントローラークラスから引数(id)を受け取ってそのままリポジトリークラスに渡すという流れです。

public List<Users> getUsers(Integer id) {
         return usersRepository.getUsers(id);
    }

そしてユーザーの一覧を取得するDTOとしてUsersListDtoを作成!
DTOってなんだ?って人は良かったら下記ページを参考にどうぞ!
こんな感じのイメージか~くらいのことしかしてませんが…
【DTOとは】

package com.example.myspringapp.dto;

import lombok.Getter;
import lombok.Setter;
import com.example.myspringapp.entity.Users;
import com.example.myspringapp.dto.UserDto;
import com.example.myspringapp.entity.Threads;
import com.example.myspringapp.dto.ThreadListDto;
import java.time.LocalDateTime;

@Getter
@Setter

public class UsersListDto {
    private Integer id;
    private String username;
    private String mailadress;
    private String password;
    private String phoneNumber;
    private boolean deleted;

    public UsersListDto(Integer id, String username, String mailadress, String password, String phoneNumber, boolean deleted) {
        this.id = id;
        this.username = username;
        this.mailadress = mailadress;
        this.password = password;
        this.phoneNumber = phoneNumber;
        this.deleted = deleted;
}
}

んで、特に兄も書いていなかったリポジトリークラスに下記を追加!

@Query("""
    SELECT new com.example.myspringapp.dto.UserListDto(
        u.id,
        u.username,
        u.mailadress,
        u.password,
        u.phoneNumber,
        u.deleted
    )
    FROM user u
    WHERE u.deleted = false AND u.id = :id
""")
// Pageable pageable = PageRequest.of(0, 3); // 1ページ3件
List<UserListDto> getUsers(@Param("id") Integer id);

完成!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?