2022/04/15 일괄(등록 수정 삭제)

파일명 ItemService.java

package com.example.service;

import java.util.List;

import com.example.entity.ItemEntity;

import org.springframework.stereotype.Service;

@Service
public interface ItemService {

    // 일괄추가
    public int insertItemBatch(List<ItemEntity> list);

    // 수정시 해당하는 항목만 조회하기
    public List<ItemEntity> selectItemEntityIn(Long[] no);

    // 일괄수정
	public int updateItemBatch(List<ItemEntity> list);
	
	// 일괄삭제
	public int deleteItemBatch(Long[] no);
    
}

파일명 ItemServiceImpl.java

package com.example.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import com.example.entity.ItemEntity;
import com.example.repository.ItemRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ItemServiceImpl implements ItemService{

    @Autowired EntityManagerFactory emf;
    @Autowired ItemRepository iRepository;

    @Override
    public int insertItemBatch(List<ItemEntity> list) {
        EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();

            //여러개 추가
            for(ItemEntity item : list){
                em.persist(item);
            }
            em.getTransaction().commit();
            return 1;
            
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
            return 0;
        }
    }

    @Override
    public List<ItemEntity> selectItemEntityIn(Long[] no) {
        
        return iRepository.findByIcodeIn(no);
    }

    @Override
    public int updateItemBatch(List<ItemEntity> list) {
        EntityManager em = emf.createEntityManager();
        try {
            em.getTransaction().begin();            
            for(ItemEntity item : list){
                // 기본키를 이용해서 기종 데이터를 꺼냄
                ItemEntity oldItem = em.find(ItemEntity.class, item.getIcode());
                oldItem.setIname( item.getIname() );
                oldItem.setIprice( item.getIprice() );
                oldItem.setIcontent( item.getIcontent() );
                oldItem.setIquantity( item.getIquantity() );
                em.persist(oldItem);
            }
            em.getTransaction().commit();
            return 1;
            
        } catch (Exception e) {
            e.printStackTrace();
            em.getTransaction().rollback();
            return 0;
        }
        
    }

    @Override
    public int deleteItemBatch(Long[] no) {
        EntityManager em = emf.createEntityManager();
		try {
			em.getTransaction().begin();
			for( Long tmp : no) {
				//기본키를 이용해서 기존 데이터를 꺼냄
				ItemEntity oldItem = em.find(ItemEntity.class, tmp);
				em.remove(oldItem);
			}
			em.getTransaction().commit();
			return 1;
		}
		catch(Exception e) {
			e.printStackTrace();
			em.getTransaction().rollback();
			return 0;
		}
    }
}

파일명 ItemRepository.java

package com.example.repository;

import java.util.List;

import com.example.entity.ItemEntity;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface ItemRepository extends JpaRepository<ItemEntity, Long> {

    List<ItemEntity> findByIcodeIn(Long[] no);
    
}

파일명 SellerController.java

package com.example.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.example.dto.ItemDTO;
import com.example.entity.BuyProjection;
import com.example.entity.ItemEntity;
import com.example.entity.MemberEntity;
import com.example.mapper.ItemMapper;
import com.example.repository.BuyRepository;
import com.example.service.ItemService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping(value = "/seller")
public class SellerController {

    // int PAGECNT = 10;
    @Value("${board.page.count}") int PAGECNT;

    @Autowired ItemMapper iMapper;          //mybatis
    @Autowired BuyRepository buyRepository; // jap+hibernate

    @Autowired ItemService iService;

    @Autowired ResourceLoader resLoader;


    @GetMapping(value = "/deleteupdatebatch")
    public String deleteUpdateBatchGET(
        Model model,
        @RequestParam(name="btn") String btn, 
        @RequestParam(name="no") Long[] no
    ){
        System.out.println("==========deleteupdatebatch==========");
        System.out.println(btn);
        System.out.println(no[0]);
        if(btn.equals("일괄수정")){
            List<ItemEntity> list = iService.selectItemEntityIn(no);
            model.addAttribute("list", list);
            return "updateitem_batch";
        }
        else if(btn.equals("일괄삭제")){
            iService.deleteItemBatch(no);
        }
        return "redirect:/seller/home";
    }

    @PostMapping(value = "/updateitembatch")
    public String updateitembatchPOST(
        @RequestParam(name = "icode") Long[] icode,
        @RequestParam(name = "iname") String[] iname,
        @RequestParam(name = "icontent") String[] icontent,
        @RequestParam(name = "iprice") Long[] iprice,
        @RequestParam(name = "iquantity") Long[] iquantity
    ){
        List<ItemEntity> list = new ArrayList<>();
        for(int i=0; i<iname.length; i++){
            ItemEntity item = new ItemEntity();
            item.setIcode(icode[i]);
            item.setIname(iname[i]);
            item.setIcontent(icontent[i]);
            item.setIprice(iprice[i]);
            item.setIquantity(iquantity[i]);
            
            list.add(item);
        }
        iService.updateItemBatch(list);
        return "redirect:/seller/home";
    }


    @GetMapping(value = "/insertitembatch")
    public String insertbatchGET(){
        return "insertitem_batch";
    }

    @PostMapping(value = "/insertitembatch")
    public String insertbatchPOST(
        @AuthenticationPrincipal User user,
        @RequestParam(name = "iname") String[] iname,
        @RequestParam(name = "icontent") String[] icontent,
        @RequestParam(name = "iprice") Long[] iprice,
        @RequestParam(name = "iquantity") Long[] iquantity,
        @RequestParam(name = "timage") MultipartFile[] iimage
    ) throws IOException{
        List<ItemEntity> list = new ArrayList<>();
        for(int i=0; i<iname.length; i++){
            System.out.println("==========insertitembatch==========");
            System.out.println(iname[i]);
            System.out.println(icontent[i]);
            System.out.println(iprice[i]);
            System.out.println(iquantity[i]);
            System.out.println(iimage[i].getOriginalFilename());
            System.out.println("==========insertitembatch==========");
            
            ItemEntity item = new ItemEntity();
            item.setIname(iname[i]);
            item.setIcontent(icontent[i]);
            item.setIprice(iprice[i]);
            item.setIquantity(iquantity[i]);
            item.setIimage(iimage[i].getBytes());
			item.setIimagename(iimage[i].getOriginalFilename());
			item.setIimagesize(iimage[i].getSize());
			item.setIimagetype(iimage[i].getContentType());
			
            MemberEntity member = new MemberEntity();
			member.setUemail(user.getUsername());
			item.setMember(member); 

            list.add(item);
        }
        iService.insertItemBatch(list);

        return "redirect:/seller/home";
    }


    @GetMapping(value = "/updateitem")
    public String updateItemGET(
        Model model,
        @AuthenticationPrincipal User user,
        @RequestParam(name = "code") long code
    ){        
        if(user != null){
            ItemDTO item = iMapper.selectItemOne(code);
            model.addAttribute("item", item);
            return "updateitem";
        }
        return "redirect:/member/login";
    }

    @PostMapping(value = "/updateitem")
    public String updateItemPOST(    
        Model model,
        @AuthenticationPrincipal User user,
        @ModelAttribute ItemDTO item,
        @RequestParam(name = "timage") MultipartFile file ) throws IOException{
        System.out.println("=============== item ===============");
        System.out.println(item.toString());
        System.out.println("파일명 : "+file.getOriginalFilename());
        if(user != null){ 
            if(!file.isEmpty()){
                item.setIimage(file.getBytes());
                item.setIimagename(file.getOriginalFilename());
                item.setIimagesize(file.getSize());
                item.setIimagetype(file.getContentType());
            }
            item.setUemail(user.getUsername());
            
            iMapper.updateItemOne(item);

            model.addAttribute("msg","물품수정 완료");
            model.addAttribute("url","/seller/home");
            return "alert";
            // return "redirect:/seller/home";
        }
        return "redirect:/member/login";
    }


    @PostMapping(value = "/deleteitem")
    public String deleteItemPOST(
        @AuthenticationPrincipal User user,
        @RequestParam(name = "code") long code
    ){        
        if(user != null){ // 로그인 되었을 경우
            System.out.println(code);            
            int ret = iMapper.deleteItemOne(code, user.getUsername());
            if(ret == 1){            
                return "redirect:/seller/home";
            }
        }
        return "redirect:/member/login";
    }


    @GetMapping(value = "/insertitem")
    public String insertItemGET(){
        return "insertitem";
    }

    @PostMapping(value = "/insertitem")
    public String insertitemPOST(
        @AuthenticationPrincipal User user,
        @ModelAttribute ItemDTO item,
        @RequestParam(name = "timage") MultipartFile file) throws IOException {
        
        // System.out.println(item.toString());
        // System.out.println(file.getOriginalFilename());

        if(user != null){ // 로그인 되었을 경우
            item.setIimage(file.getBytes());
            item.setIimagename(file.getOriginalFilename());
            item.setIimagesize(file.getSize());
            item.setIimagetype(file.getContentType());

            item.setUemail(user.getUsername());

            iMapper.insertItemOne(item);

            return "redirect:/seller/home";
        }
        // 로그인 되지 않았을 경우
        return "redirect:/member/login";
    }


    // 127.0.0.1:9090/ROOT/seller
    // 127.0.0.1:9090/ROOT/seller/home
    @GetMapping(value = {"/","/home"})
    public String sellerGET(
        Model model,
        @RequestParam(name = "page", defaultValue = "1") int page,
        @RequestParam(name = "txt", defaultValue = "") String txt,
        @AuthenticationPrincipal User user
    ){
        if(user != null){
            // 목록
            List<ItemDTO> list = iMapper.selectItemList(
                user.getUsername(),
                txt,
                (page * PAGECNT)-(PAGECNT - 1),
                page * PAGECNT );
            model.addAttribute("list",list);

            // 페이지네이션 개수
            long cnt = iMapper.selectItemCount(
                user.getUsername(),txt);
            model.addAttribute("pages",(cnt -1)/ PAGECNT + 1);           
            
            // 주문 내역
            List<Long> list1 = new ArrayList<>();
            for( ItemDTO item : list ){
                list1.add( item.getIcode() );
            }
            List<BuyProjection> list2 = buyRepository.findByItem_icodeIn( list1 );
            model.addAttribute("list2",list2);

            return "seller_home";
        }
        return "redirect:/member/login";
    }
}

파일명 seller_home.html

일부

<div style="padding: 10px;">

		<a th:href="@{/seller/insertitem}">물품등록</a>
		<a th:href="@{/seller/insertitembatch}">물품일괄등록</a>

        <form th:action="@{/seller/home}" method="get">
            <input type="text" name="txt" placeholder="검색어" />
            <input type="submit" value="검색" />
        </form>
        
		<form th:action="@{/seller/deleteupdatebatch}" method="get">
			<input type="submit" name="btn" value="일괄수정" />
			<input type="submit" name="btn" value="일괄삭제" />

			<table border="1">
				<tr>
					<th>체크</th>
					<th>번호</th>
					<th>물품코드</th>
					<th>물품명</th>
					<th>가격</th>
					<th>수량</th>
					<th>등록일</th>
					<th>버튼</th>
				</tr>		
				<tr th:each="tmp, idx : ${list}">
					<td><input type="checkbox" th:value="${tmp.icode}" name="no" /> </td>
					<td th:text="${idx.count}"></td>
					<td>
						<a th:href="@{/seller/home(code=${tmp.icode})}"
							th:text="${tmp.icode}"></a>
					</td>
					<td th:text="${tmp.iname}"></td>
					<td th:text="${tmp.iprice}"></td>
					<td th:text="${tmp.iquantity}"></td>
					<td th:text="${tmp.iregdate}"></td>
					<td >					
						<button th:onclick="|javascript:handleUpdate('${tmp.icode}')|">수정</button>
						<button th:onclick="|javascript:handleDelete('${tmp.icode}')|">삭제</button>
					</td>
				</tr> 
			</table>
		</form>

		<th:block th:each="i : ${#numbers.sequence(1, pages)}">
			<a th:href="@{/seller/home(page=${i}, txt=${param.txt})}" th:text="${i}"></a>
		</th:block>   

파일명 insertitem_batch.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>물품일괄등록</title>
</head>

<body style="padding: 10px;">
    <h3>물품 일괄 등록 페이지 입니다.</h3>

    <hr />

    <div style="padding: 20px;">        
        <form th:action="@{/seller/insertitembatch}" method="post" enctype="multipart/form-data">
            <th:block th:each="i : ${#numbers.sequence(1,2)}">
                <label style="width:75px; height: 30px; display:inline-block;">물품명 : </label>
                <input type="text" placeholder="물품명" name="iname"/></br>

                <label style="width:75px; height: 30px; display:inline-block;">물품내용 : </label>
                <textarea cols="30" rows="10" placeholder="물품내용" name="icontent"></textarea><br />            

                <label style="width:75px; height: 30px; display:inline-block;">물품가격 : </label>
                <input type="text" placeholder="물품가격" name="iprice"/></br>

                <label style="width:75px; height: 30px; display:inline-block;">물품수량 : </label>
                <input type="text" placeholder="물품수량" name="iquantity"/></br>

                <label style="width:75px; height: 30px; display:inline-block;">이미지 : </label>
                <input type="file" name="timage"></br>
                <hr />
            </th:block>
            <label style="width:75px; height: 30px; display:inline-block;"></label>                    
            <input type="submit"  value="물품등록" />
        </form>        
    </div>    
</body>
</html>

파일명 updateitem_batch.html

<!DOCTYPE html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>물품일괄수정</title>
</head>

<body style="padding: 10px;">
    <h3>물품 일괄 수정 페이지 입니다.</h3>

    <hr />

    <div style="padding: 20px;">        
        <form th:action="@{/seller/updateitembatch}" method="post">
            <div th:each="item : ${list}">
                <label style="width:75px; height: 30px; display:inline-block;">물품코드 : </label>
                <input type="text"  name="icode" th:value="${item.icode}" readonly/></br>

                <label style="width:75px; height: 30px; display:inline-block;">물품명 : </label>
                <input type="text"  name="iname" th:value="${item.iname}"/></br>

                <label style="width:75px; height: 30px; display:inline-block;">물품내용 : </label>
                <input cols="30" rows="10"  name="icontent" th:value="${item.icontent}"></input><br />            

                <label style="width:75px; height: 30px; display:inline-block;">물품가격 : </label>
                <input type="text" placeholder="물품가격" name="iprice" th:value="${item.iprice}"/></br>

                <label style="width:75px; height: 30px; display:inline-block;">물품수량 : </label>
                <input type="text" placeholder="물품수량" name="iquantity" th:value="${item.iquantity}"/></br>                
                <hr />
            </div>
            <label style="width:75px; height: 30px; display:inline-block;"></label>                    
            <input type="submit"  value="물품등록" />

            <a th:href="@{/seller/home}">목록으로</a>

        </form>        
    </div>    
</body>
</html>

좋은 웹페이지 즐겨찾기