package com.sbp.copyrightStreet.boundedContext.cart;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import com.sbp.copyrightStreet.boundedContext.store.Store;
import java.time.LocalDateTime;
@Getter
@Setter
@Entity
public class Cart {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String title;
private String content;
private LocalDateTime create_Date;
private String filepath;
private String filename;
private int hitCount;
private String category;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "store_id")
private Store store;
public String getFile() {
return filepath.replaceAll("/Users/munchangbin/Downloads/copyright_street/src/main/resources/static", "");
}
}
현재 장바구니 entity는 이렇게 설정이되어있다.
package com.sbp.copyrightStreet.boundedContext.cart;
import com.sbp.copyrightStreet.boundedContext.store.StoreService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
@Controller
@RequiredArgsConstructor
public class CartController {
private final StoreService storeService;
private final CartService cartService;
@GetMapping("/store/cart")
public String cart(Model model) {
List<Cart> cartItems = cartService.getCartItems();
model.addAttribute("cartItems", cartItems);
return "usr/home/copy_cart";
}
@PostMapping("/store/cart")
public String addToCart(@RequestParam("id") Integer id) {
this.storeService.cart(id);
return "redirect:/store/cart";
}
@GetMapping("/store/cart/delete/{id}")
public String deleteCartItem(@PathVariable("id") Integer id) {
this.cartService.deleteCartItem(id); // 카트 내용 삭제 메서드 추가
return "redirect:/store/cart";
}
} 컨트롤쪽에 store id 값을 불러와서 따로 저장할수있게 해놓았고 .
package com.sbp.copyrightStreet.boundedContext.cart;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
@RequiredArgsConstructor
public class CartService {
private final CartRepository cartRepository;
public List<Cart> getCartItems() {
return cartRepository.findAll();
}
public void deleteCartItem(Integer id) {
cartRepository.deleteById(id);
}
public void deleteCartItemsByStoreId(Integer storeId) {
List<Cart> cartList = cartRepository.findByStoreId(storeId);
cartRepository.deleteAll(cartList);
}
}
서비스쪽 코드는 이거다.
레포지토리에 package com.sbp.copyrightStreet.boundedContext.cart;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface CartRepository extends JpaRepository<Cart, Integer> {
List<Cart> findByStoreId(Integer StoreId);
}
package com.sbp.copyrightStreet.boundedContext.store;
import com.sbp.copyrightStreet.boundedContext.cart.Cart;
import com.sbp.copyrightStreet.boundedContext.cart.CartRepository;
import com.sbp.copyrightStreet.boundedContext.cart.CartService;
import com.sbp.copyrightStreet.boundedContext.home.controller.DataNotFoundException;
import jakarta.transaction.Transactional;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Service
@RequiredArgsConstructor
public class StoreService {
private final StoreRepository storeRepository;
private final CartRepository cartRepository;
private final CartService cartService;
public static void increaseHitCount() {
}
public void create(String title, String content, String category, MultipartFile file) throws Exception {
String projectPath = System.getProperty("user.dir") + "//src//main//resources//static//files";
UUID uuid = UUID.randomUUID();
String fileName = uuid + "_" + file.getOriginalFilename();
File savefile = new File(projectPath, fileName);
file.transferTo(savefile);
Store store = new Store();
store.setTitle(title);
store.setContent(content);
store.setCategory(category);
store.setCreate_Date(LocalDateTime.now());
store.setFilepath(savefile.toString());
store.setFilename(fileName);
this.storeRepository.save(store);
}
public Page<Store> getList(int page, String kw) {
Pageable pageable = PageRequest.of(page, 3); // page 값 1 감소
return this.storeRepository.findAll(pageable);
}
public Store getStore(Integer id) {
Optional<Store> store = this.storeRepository.findById(id);
if (store.isPresent()) {
Store store1 = store.get();
store1.setHitCount(store1.getHitCount() + 1);
this.storeRepository.save(store1);
return store1;
} else {
throw new DataNotFoundException("store not found");
}
}
public void modify(Integer id, String title, String content, String category, MultipartFile file) throws Exception {
Store store = getStore(id);
if (store == null) {
throw new Exception("해당 id가 없습니다");
}
String projectPath = System.getProperty("user.dir") + "//src//main//resources//static//files";
UUID uuid = UUID.randomUUID();
String fileName = uuid + "_" + file.getOriginalFilename();
File savefile = new File(projectPath, fileName);
file.transferTo(savefile);
store.setTitle(title);
store.setContent(content);
store.setCategory(category);
store.setFilename(fileName);
store.setFilepath(savefile.toString());
this.storeRepository.save(store);
}
@Transactional
public void delete(Integer storeId) {
Store store = this.getStore(storeId);
List<Cart> cartList = this.cartRepository.findByStoreId(storeId);
this.cartRepository.deleteAll(cartList);
this.storeRepository.delete(store);
}
public void cart(Integer id) {
Optional<Store> store = this.storeRepository.findById(id);
if (store.isPresent()) {
Store store1 = store.get();
Cart cart = new Cart();
cart.setTitle(store1.getTitle());
cart.setContent(store1.getContent());
cart.setCreate_Date(LocalDateTime.now());
cart.setFilepath(store1.getFilepath());
cart.setFilename(store1.getFilename());
cart.setCategory(store1.getCategory());
cart.setStore(store1);
this.cartRepository.save(cart);
}
}
}
package com.sbp.copyrightStreet.boundedContext.store;
import com.sbp.copyrightStreet.boundedContext.cart.Cart;
import com.sbp.copyrightStreet.boundedContext.cart.CartRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
@Controller
@RequiredArgsConstructor
public class StoreController {
private final StoreService storeService;
private final CartRepository cartRepository;
@GetMapping("/store/create")
public String create(Store store) {
return "usr/home/copy_form";
}
@PostMapping("/store/create")
public String create(@RequestParam String title,
@RequestParam String content,
@RequestParam String category,
@RequestParam(required = false) MultipartFile file) throws Exception {
this.storeService.create(title, content, category, file);
return "redirect:/copy/store";
}
@GetMapping("/store/detail/{id}")
public String detail(Model model, @PathVariable("id") Integer id) {
StoreService.increaseHitCount();
Store store = this.storeService.getStore(id);
model.addAttribute("store", store);
model.addAttribute("id", id); // id 값을 모델에 추가하여 장바구니에 추가할 때 사용
return "/usr/home/copy_detail";
}
@GetMapping("/store/modify/{id}")
public String modify(Store store)
{
return "usr/home/copy_modify";
}
@PostMapping("/store/modify/{id}")
public String modify(@PathVariable("id") Integer id, @RequestParam String title, @RequestParam String content, @RequestParam String category, @RequestParam(required = false) MultipartFile file)
throws Exception {
Store store = this.storeService.getStore(id);
this.storeService.modify(id, title, content, category, file);
return "redirect:/copy/store";
}
@GetMapping("/store/delete/{id}")
public String delete(@PathVariable("id") Integer id) {
this.storeService.delete(id);
return "redirect:/copy/store";
}
}
쪽 코드로 스토어글 삭제시 장바구니에 담긴 값도 같이 삭제를할수있게 코드를짯다
즐겁게 읽었습니다. 유용한 정보 감사합니다.