티스토리 뷰

728x90

1. 이 포스트는 Spring Web + Hibernate Update와 연결되는 포스트이다.

 

2. 고객 정보를 삭제하는 기능을 추가한다.

  2-1 list-customers.jsp에 고객리스트의 update링크 옆에 delete를 추가한다.

  2-2 CustomerDAO와 구현클래스에 deleteCustomer 메소드를 추가한다.

  2-3 CustomerService와 구현클래스에 deleteCustomer메소드를 추가한다.

  2-4 CustomerController에 수정된 CustomerService를 사용하도록 변경한다.

 

3. 고객 리스트에 delete링크를 추가한다.

  3-1 추가된 부분은 c:url의 deleteLink 변수와 링크에서 사용하는 부분이다.

  3-2 링크를 클릭시 confirm박스를 화면에 띄어 한번 더 삭제여부를 확인한다.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet"
  href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
  integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh"
  crossorigin="anonymous">
<link rel="stylesheet" href="${pageContext.request.contextPath}/resources/css/sytle.css"/>
<title>List of Customers</title>
</head>
<body>
  <div class="container">
    <h2 class="mb-5 mt-5">CRM - Customer Relationship Manager</h2>
    <a href="showAddCustomerForm" class="btn btn-secondary mb-3">Add Customer</a>
    <table class="table">
      <thead>
        <tr>
          <th>First Name</th>
          <th>Last Name</th>
          <th>Email</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        <c:forEach var="customer" items="${ customers }">
          <c:url var="updateLink" value="showUpdateCustomerForm">
            <c:param name="id" value="${ customer.id }"></c:param>
          </c:url>
          <c:url var="deleteLink" value="deleteCustomer">
            <c:param name="id" value="${ customer.id }"></c:param>
          </c:url>
          
          <tr>
            <td>${ customer.firstName }</td>
            <td>${ customer.lastName }</td>
            <td>${ customer.email }</td>
            <td>
              <a href="${ updateLink }">Update</a> | 
              <a href="${ deleteLink }" onclick="if (!confirm('Do you really want to delete?')) return false">Delete</a>
            </td>
          </tr>
        </c:forEach>
      </tbody>
    </table>
  </div>
  <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"
    integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"
    crossorigin="anonymous"></script>
  <script
    src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
    integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
    crossorigin="anonymous"></script>
  <script
    src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"
    integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6"
    crossorigin="anonymous"></script>
</body>
</html>

4. CustomerDAO에 delete 기능을 추가한다.

  4-1 추가된 deleteCustomer메소드는 id를 가지고 삭제하는 기능이기 때문에 HQL을 사용하였다.

  4-2 setNamedParameter가 deprecated되어 setParameter를 사용했다.

public interface CustomerDAO {
  List<Customer> getCustomers();
  void saveCustomer(Customer customer);
  Customer getCustomer(Long id);
  void deleteCustomer(Long id);
}


@Repository
public class CustomerDAOImpl implements CustomerDAO {

  @Autowired
  private SessionFactory sessionFactory;

  @Override
  public List<Customer> getCustomers() {
    Session session = this.sessionFactory.getCurrentSession();

    return session.createQuery("from Customer order by firstName", Customer.class).getResultList();
  }

  @Override
  public void saveCustomer(Customer customer) {
    Session session = this.sessionFactory.getCurrentSession();
    
    session.saveOrUpdate(customer);
  }

  @Override
  public Customer getCustomer(Long id) {
    Session session = this.sessionFactory.getCurrentSession();
    
    return session.get(Customer.class, id);
  }

  @Override
  public void deleteCustomer(Long id) {
    Session session = this.sessionFactory.getCurrentSession();
    
    String deleteQuery = "delete from Customer where id=:id";
    session.createQuery(deleteQuery).setParameter("id", id).executeUpdate();
  }
}

5. CustomerService에 삭제기능을 구현한다.

public interface CustomerService {
  List<Customer> getCustomers();
  void saveCustomer(Customer customer);
  Customer getCustomer(Long id);
  void deleteCustomer(Long id);
}

@Service
public class CustomerServiceImpl implements CustomerService {

  @Autowired
  private CustomerDAO customerDAO;
  
  @Override
  @Transactional
  public List<Customer> getCustomers() {
    return this.customerDAO.getCustomers();
  }

  @Override
  @Transactional
  public void saveCustomer(Customer customer) {
    this.customerDAO.saveCustomer(customer);
  }

  @Override
  @Transactional
  public Customer getCustomer(Long id) {
    return this.customerDAO.getCustomer(id);
  }

  @Override
  @Transactional
  public void deleteCustomer(Long id) {
    this.customerDAO.deleteCustomer(id);
  }
}

6. Controller에서 삭제기능을 처리하는 매핑 추가

@Controller
@RequestMapping("/customer")
public class CustomerController {
  
  @Autowired
  private CustomerService customerService;
  
  @GetMapping("/list")
  public String listCustomers(Model model) {
    
    model.addAttribute("customers", this.customerService.getCustomers());
    
    return "list-customers";
  }
  
  @GetMapping("/showAddCustomerForm")
  public String showAddCustomerForm(Model model) {
    model.addAttribute("customer", new Customer());
    
    return "customer-form";
  }
  
  @PostMapping("/saveCustomer")
  public String saveCustomer(@ModelAttribute Customer customer) {
    this.customerService.saveCustomer(customer);
    return "redirect:/customer/list";
  }
  
  @GetMapping("/showUpdateCustomerForm")
  public String showUpdateCustomerForm(@RequestParam("id") Long id, Model model) {
    
    model.addAttribute("customer", this.customerService.getCustomer(id));
    
    return "customer-form";
  }
  
  @GetMapping("/deleteCustomer")
  public String deleteCustomer(@RequestParam("id") Long id) {
    
    this.customerService.deleteCustomer(id);
    
    return "redirect:/customer/list";
  }
}
728x90
댓글