Skip to content

Commit

Permalink
Merge pull request #30 from UMC-HACKATHON-SnapSpot/feat/#24
Browse files Browse the repository at this point in the history
Feat/#24
  • Loading branch information
wonjun0120 authored Jul 4, 2024
2 parents 2183c12 + dbaa2d0 commit 0c69d52
Show file tree
Hide file tree
Showing 10 changed files with 271 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package com.umc.hackaton.snapspot.category.controller;

import com.umc.hackaton.snapspot.category.dto.CategoryRequestDto;
import com.umc.hackaton.snapspot.category.entity.Category;
import com.umc.hackaton.snapspot.category.service.CategoryService;
import com.umc.hackaton.snapspot.savespot.dto.UserFolderRequestDto;
import com.umc.hackaton.snapspot.spot.entity.Spot;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RequiredArgsConstructor
@RestController
@Slf4j
@RequestMapping("/api/v1/categories")
public class CategoryController {
private final CategoryService categoryService;

@PostMapping("/")
public ResponseEntity<?> createCategory(@RequestBody CategoryRequestDto category) {
try {
categoryService.save(category);
return ResponseEntity.ok().body(category);
} catch (Exception e){
log.info("카테고리 생성에 실패하였습니다.", e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("카테고리 생성에 실패하였습니다.");
}
}


@GetMapping("/")
public ResponseEntity<?> showAllCategories() {
try {
List<Category> categories = categoryService.showAll();
return ResponseEntity.ok().body(categories);
} catch (Exception e){
log.info("카테고리 리스트 조회에 실패하였습니다.", e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("카테고리 리스트 조회에 실패하였습니다.");
}
}

@GetMapping("/spots")
public ResponseEntity<?> showSpotsByCategoryId(
@RequestParam List<Long> categoryIds
) {
try {
List<Spot> spots = categoryService.showSpotsByCategoryIds(categoryIds);
return ResponseEntity.ok().body(spots);
} catch (Exception e){
log.info("카테고리별 스팟 리스트 조회에 실패하였습니다.", e);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("카테고리별 스팟 리스트 조회에 실패하였습니다.");
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.umc.hackaton.snapspot.category.dto;

import com.umc.hackaton.snapspot.category.entity.Category;
import jakarta.validation.constraints.NotNull;
import lombok.Builder;
import lombok.Getter;

@Getter
public class CategoryRequestDto {
@NotNull private String categoryName;

@Builder
public Category toEntity() {
return Category.builder()
.categoryName(categoryName)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.umc.hackaton.snapspot.category.entity;

import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.umc.hackaton.snapspot.config.entity.BaseEntity;
import jakarta.persistence.*;
import lombok.*;

import java.util.LinkedHashSet;
import java.util.Set;

@Entity
@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Category extends BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@Column(name = "category_name", nullable = false)
private String categoryName;

@ToString.Exclude
@JsonManagedReference
@OrderBy("id")
@OneToMany(mappedBy = "category")
private final Set<CategorySpot> categorySpots = new LinkedHashSet<>();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package com.umc.hackaton.snapspot.category.entity;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.umc.hackaton.snapspot.config.entity.BaseEntity;
import com.umc.hackaton.snapspot.spot.entity.Spot;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Entity
@Getter
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class CategorySpot extends BaseEntity{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "spot_id")
@JsonBackReference
private Spot spot;

@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "category_id")
@JsonBackReference
private Category category;


}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.umc.hackaton.snapspot.category.repository;

import com.umc.hackaton.snapspot.category.entity.Category;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

import java.util.List;

public interface CategoryRepository extends JpaRepository<Category, Long> {
@Query("SELECT c.id, c.categoryName FROM Category c")
List<Object[]> findAllCategories();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.umc.hackaton.snapspot.category.repository;

import com.umc.hackaton.snapspot.category.entity.Category;
import com.umc.hackaton.snapspot.category.entity.CategorySpot;
import org.springframework.data.jpa.repository.JpaRepository;

import java.util.List;

public interface CategorySpotRepository extends JpaRepository<CategorySpot, Long> {
List<CategorySpot> findAllByCategory(Category category);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package com.umc.hackaton.snapspot.category.service;

import com.umc.hackaton.snapspot.category.dto.CategoryRequestDto;
import com.umc.hackaton.snapspot.category.entity.Category;
import com.umc.hackaton.snapspot.category.entity.CategorySpot;
import com.umc.hackaton.snapspot.category.repository.CategoryRepository;
import com.umc.hackaton.snapspot.category.repository.CategorySpotRepository;
import com.umc.hackaton.snapspot.spot.dto.SpotDto;
import com.umc.hackaton.snapspot.spot.entity.Spot;
import com.umc.hackaton.snapspot.user.entity.User;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CategoryService {
private final CategoryRepository categoryRepository;
private final CategorySpotRepository categorySpotRepository;


public void save(CategoryRequestDto category) {
categoryRepository.save(category.toEntity());
}

public List<Category> showAll() {
List<Object[]> objects = categoryRepository.findAllCategories();
return objects.stream()
.map(object -> new Category((Long) object[0], (String) object[1]))
.collect(Collectors.toList());
}

public List<Spot> showSpotsByCategoryIds(List<Long> categoryIds) {
Set<Spot> spots = new HashSet<>();
for (Long categoryId : categoryIds) {
Category category = categoryRepository.findById(categoryId).orElse(null);
if (category != null) {
List<CategorySpot> categorySpots = categorySpotRepository.findAllByCategory(category);
List<Spot> categorySpotsMapped = categorySpots.stream()
.map(CategorySpot::getSpot)
.collect(Collectors.toList());
spots.addAll(categorySpotsMapped);
}
// if (category != null) {
// List<CategorySpot> categorySpots = categorySpotRepository.findAllByCategory(category);
// for (CategorySpot categorySpot : categorySpots) {
// SpotDto spotDto = new SpotDto();
// User user = categorySpot.getSpot().getUser();
// spotDto.setUser(user);
// spotDto.setLatitude(categorySpot.getSpot().getLatitude());
// spotDto.setLongitude(categorySpot.getSpot().getLongitude());
// spotDto.setTitle(categorySpot.getSpot().getTitle());
// spotDto.setDescription(categorySpot.getSpot().getDescription());
// spotDto.setImgUrl(categorySpot.getSpot().getImgUrl());
//
// Spot spot = spotDto.toEntity();
// spots.add(spot);
// }
// }
}
return new ArrayList<>(spots);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import lombok.Builder;
import lombok.Getter;

import java.util.List;

@Getter
public class SpotRequestDto {
private Long userId;
Expand All @@ -12,5 +14,6 @@ public class SpotRequestDto {
private String title;
private String description;
private String imgUrl;
private List<Long> categoryNums;

}
16 changes: 11 additions & 5 deletions src/main/java/com/umc/hackaton/snapspot/spot/entity/Spot.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;
import java.util.Objects;

@Entity
@Getter
Expand All @@ -22,7 +23,7 @@ public class Spot extends BaseEntity {
@Column(name = "id")
private Long id;

@ManyToOne(fetch = FetchType.LAZY)
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "user_id", nullable = false)
private User user;

Expand All @@ -47,11 +48,16 @@ public class Spot extends BaseEntity {
@Column(name = "description", nullable = false, columnDefinition = "TEXT")
private String description;

public void increaseLike() {
this.likeNum -= 1;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Spot spot = (Spot) o;
return Objects.equals(id, spot.id);
}

public void decreaseLike() {
this.likeNum += 1;
@Override
public int hashCode() {
return Objects.hashCode(id);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
package com.umc.hackaton.snapspot.spot.service;

import com.umc.hackaton.snapspot.category.entity.Category;
import com.umc.hackaton.snapspot.category.entity.CategorySpot;
import com.umc.hackaton.snapspot.category.repository.CategoryRepository;
import com.umc.hackaton.snapspot.category.repository.CategorySpotRepository;
import com.umc.hackaton.snapspot.spot.dto.SpotDto;
import com.umc.hackaton.snapspot.spot.dto.SpotRequestDto;
import com.umc.hackaton.snapspot.spot.entity.Spot;
Expand All @@ -11,11 +15,17 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class SpotService {
private final SpotRepository spotRepository;
private final UserRepository userRepository;
private final CategoryRepository categoryRepository;
private final CategorySpotRepository categorySpotRepository;

@Transactional
public void upload(SpotRequestDto dto) {
Expand All @@ -30,7 +40,22 @@ public void upload(SpotRequestDto dto) {
spotDto.setDescription(dto.getDescription());
spotDto.setImgUrl(dto.getImgUrl());

spotRepository.save(spotDto.toEntity());
Spot savedSpot = spotRepository.save(spotDto.toEntity());

List<CategorySpot> categorySpots = new ArrayList<>();
for (Long categoryId : dto.getCategoryNums()) {
Optional<Category> categoryOptional = categoryRepository.findById(categoryId);
categoryOptional.ifPresent(category -> {
CategorySpot categorySpot = CategorySpot.builder()
.category(category)
.spot(savedSpot)
.build();
categorySpots.add(categorySpot);
});
}

// CategorySpot 저장
categorySpotRepository.saveAll(categorySpots);

}
}

0 comments on commit 0c69d52

Please sign in to comment.