Spring Boot/[Spring boot] 개발

[Spring boot] Link 데이터베이스 생성, 기능 추가

재윤 2025. 1. 5. 16:56
반응형

LinksController

package com.Kkrap.Controller;

import com.Kkrap.RequestDTO.LinksDTO;
import com.Kkrap.RequestDTO.LinksDeleteDTO;
import com.Kkrap.ResponseDto.LinksResponseDTO;
import com.Kkrap.ResponseDto.MessageResponseDTO;
import com.Kkrap.Service.LinksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/v1")
public class LinksController {
    @Autowired
    private LinksService linksService;

    @GetMapping("/links")
    public List<LinksResponseDTO> SelectedMemberLinks(@RequestParam(name = "userId") Long user_id){
        return linksService.SelectedMemberLinks(user_id);
    }

    @PostMapping("/links/create")
    @ResponseBody
    public ResponseEntity<MessageResponseDTO> createLink(@RequestBody LinksDTO linksDTO){
        linksService.createLink(linksDTO.getUserId(), linksDTO.getLinkUrl());
        MessageResponseDTO responseDTO = new MessageResponseDTO("create Link Success");
        return ResponseEntity.ok(responseDTO);
    }

    @PostMapping("/links/delete")
    public ResponseEntity<LinksDeleteDTO> deleteLink(@RequestBody LinksDeleteDTO linksDeleteDTO) {
        System.out.println("UserId: " + linksDeleteDTO.getUserId());

        // LinkId가 null이 아닌지 확인한 후 출력
        if (linksDeleteDTO.getLinkId() != null) {
            for (Long linkId : linksDeleteDTO.getLinkId()) {
                System.out.println("LinkId: " + linkId);
            }
        } else {
            System.out.println("LinkId 리스트가 비어있습니다.");
        }

        linksService.deleteLink(linksDeleteDTO);
        //삭제 된 걸 보내주자
        return ResponseEntity.ok(linksDeleteDTO);
    }

}

 

API 설명

/v1/links?userId={userId}

  • 현재 로그인한 사용자의 아이디값을 RequestParam으로 userId를 주면 사용자가 가지고 있는 url을 전부 준다.
    • Selected
  • 매개변수
    • userId={userId}
  @GetMapping("/links")
  public List<LinksResponseDTO> SelectedMemberLinks(@RequestParam(name = "userId") Long user_id){
      return linksService.SelectedMemberLinks(user_id);
  }

/v1/links/create

  • LinksDTO
public class LinksDTO {
    @Getter
    private Long userId;

    @Getter
    private String linkUrl;
}
  • Url을 create하는 api
  • LinksDTO에서 userId와 linkUrl을 보내주면 된다.
    @PostMapping("/links/create")
    @ResponseBody
    public ResponseEntity<MessageResponseDTO> createLink(@RequestBody LinksDTO linksDTO){
        linksService.createLink(linksDTO.getUserId(), linksDTO.getLinkUrl());
        MessageResponseDTO responseDTO = new MessageResponseDTO("create Link Success");
        return ResponseEntity.ok(responseDTO);
    }
  • responseDTO
public class MessageResponseDTO {
    private String message;

    public MessageResponseDTO(String message) {
        this.message = message;
    }
}
  • 반환되는 JSON
{
    "message": "create Link Success"
}

/v1/links/delete

  • LinksDeleteDTO
  • userId → 사용자의 아이디
  • linkId → 삭제할 url 링크 배열로 받기 가능 즉, 여러 개 삭제 가능
public class LinksDeleteDTO {
    private Long userId;
    private List<Long> linkId;
}

  • 코드
    @PostMapping("/links/delete")
    public ResponseEntity<LinksDeleteDTO> deleteLink(@RequestBody LinksDeleteDTO linksDeleteDTO) {
        System.out.println("UserId: " + linksDeleteDTO.getUserId());

        // LinkId가 null이 아닌지 확인한 후 출력
        if (linksDeleteDTO.getLinkId() != null) {
            for (Long linkId : linksDeleteDTO.getLinkId()) {
                System.out.println("LinkId: " + linkId);
            }
        } else {
            System.out.println("LinkId 리스트가 비어있습니다.");
        }

        linksService.deleteLink(linksDeleteDTO);
        //삭제 된 걸 보내주자
        return ResponseEntity.ok(linksDeleteDTO);
    }

요청값 예시

{
    "userId": 1,
    "linkId": [10,11]
}
  • 반환값은 LinksDeleteDTO 그대로
{
    "userId": 1,
    "linkId": [
        10,
        11
    ]
}

 

LinksService

package com.Kkrap.Service;

import com.Kkrap.Entity.Links;
import com.Kkrap.Entity.Users;
import com.Kkrap.Repository.LinksRepository;
import com.Kkrap.Repository.UsersRepository;
import com.Kkrap.RequestDTO.LinksDeleteDTO;
import com.Kkrap.ResponseDto.LinksResponseDTO;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class LinksService {

    @Autowired
    private UsersRepository usersRepository;
    @Autowired
    private LinksRepository linksRepository;

    //유저별 링크 조회
    public List<LinksResponseDTO> SelectedMemberLinks(Long user_id){
        List<Links> links = linksRepository.findByUsers_UserId(user_id);
        return links.stream()
                .map(link -> new LinksResponseDTO(link.getLinkId(), link.getLinkUrl(), link.getUsers().getUserId()))
                .collect(Collectors.toList());
    }

    //유저별 링크 만들기
    public void createLink(Long user_id, String linkUrl){
        System.out.println(user_id);
        Users user = usersRepository.findById(user_id).orElseThrow(() -> new IllegalArgumentException("Invalid user ID: " + user_id));
        // Links 엔티티 생성
        Links link = Links.builder()
                .users(user)
                .link_url(linkUrl)
                .build();
        // 링크 저장
        linksRepository.save(link);
    }

    public void deleteLink(LinksDeleteDTO linksDeleteDTO){
        List<Links> userLinks = linksRepository.findByUsers_UserId(linksDeleteDTO.getUserId());
        if (userLinks == null || userLinks.isEmpty())
        {
            throw new IllegalArgumentException("해당 사용자에 대한 링크가 없습니다.");
        }

        List<Links> linksToDelete = userLinks.stream() //userLinks는 Link 객체들의 리스트이다. 여기서 .stream() 메서드는 리스트를 스트림(Stream)으로 변환한다. 스트림을 사용하면 컬렉션에 대해 여러 가지 처리를 더 간결하고 효율적으로 할 수 있다
                .filter(links -> linksDeleteDTO.getLinkId().contains(links.getLinkId()))//
                .collect(Collectors.toList());

        if (linksToDelete.isEmpty()){
            throw new IllegalArgumentException("삭제할 링크 ID 값이 존재하지 않습니다.");
        }

        linksRepository.deleteAll(linksToDelete);
    }

}

 

Links(entity)

package com.Kkrap.Entity;

import com.fasterxml.jackson.annotation.JsonBackReference;
import jakarta.persistence.*;
import lombok.Builder;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import java.time.LocalDateTime;
import java.util.List;

@Entity
@Setter
@Getter
@Table(name = "links")
@EntityListeners(AuditingEntityListener.class) // Enables JPA Auditing
public class Links {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long linkId;

    @ManyToOne
    @JoinColumn(nullable = false, name = "user_id")
//    @JsonBackReference // 순환 참조 방지
    private Users users;

    @Column(nullable = false)
    private String linkUrl;

    @Column(nullable = false)
    @CreationTimestamp
    private LocalDateTime createTime;

    @OneToMany(mappedBy = "link", cascade = CascadeType.ALL)
    private List<FolderList> folderList;

    @Builder
    public Links(Users users, String link_url)
    {
        this.users = users;
        this.linkUrl = link_url;
    }

    public Links(){

    }
}

LinksResponseDTO

package com.Kkrap.ResponseDto;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class LinksResponseDTO {
    private Long linkId;
    private String linkUrl;
    private Long userId;

    public LinksResponseDTO(Long linkId, String linkUrl, Long userId) {
        this.linkId = linkId;
        this.linkUrl = linkUrl;
        this.userId = userId;
    }
}

 

LinksDTO

package com.Kkrap.RequestDTO;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class LinksDTO {
    @Getter
    private Long userId;

    @Getter
    private String linkUrl;

}

 

LinksDeleteDTO

package com.Kkrap.RequestDTO;

import lombok.Getter;
import lombok.Setter;

import java.util.List;

@Getter
@Setter
public class LinksDeleteDTO {
    private Long userId;
    private List<Long> linkId;
}

반응형