首页 > 解决方案 > 如何在 Spring Boot + Hibernate 中实现“删除”方法

问题描述

我正在尝试使用@\RequestMapping 方法编写删除产品方法:requestMethod.DELETE。这是我的 AdminController 类:

    package com.webapp.agroxapp.controller; 
import java.util.List;

import org.apache.commons.lang.exception.ExceptionUtils;
import com.webapp.agroxapp.dao.OrderDAO;
import com.webapp.agroxapp.dao.ProductDAO;
import com.webapp.agroxapp.entity.Product;
import com.webapp.agroxapp.form.ProductForm;
import com.webapp.agroxapp.model.OrderDetailInfo;
import com.webapp.agroxapp.model.OrderInfo;
import com.webapp.agroxapp.pagination.PaginationResult;
import com.webapp.agroxapp.validator.ProductFormValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;



import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
@Transactional
public class AdminController {

   @Autowired
   private OrderDAO orderDAO;

   @Autowired
   private ProductDAO productDAO;

   @Autowired
   private ProductFormValidator productFormValidator;


   @InitBinder
   public void myInitBinder(WebDataBinder dataBinder) {
      Object target = dataBinder.getTarget();
      if (target == null) {
         return;
      }
      System.out.println("Target=" + target);

      if (target.getClass() == ProductForm.class) {
         dataBinder.setValidator(productFormValidator);
      }
   }

   // GET: Show Login Page
   @RequestMapping(value = { "/admin/login" }, method = RequestMethod.GET)
   public String login(Model model) {

      return "login";
   }

   @RequestMapping(value = { "/admin/accountInfo" }, method = RequestMethod.GET)
   public String accountInfo(Model model) {

      UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
      System.out.println(userDetails.getPassword());
      System.out.println(userDetails.getUsername());
      System.out.println(userDetails.isEnabled());

      model.addAttribute("userDetails", userDetails);
      return "accountInfo";
   }

   @RequestMapping(value = { "/admin/orderList" }, method = RequestMethod.GET)
   public String orderList(Model model, //
         @RequestParam(value = "page", defaultValue = "1") String pageStr) {
      int page = 1;
      try {
         page = Integer.parseInt(pageStr);
      } catch (Exception e) {
      }
      final int MAX_RESULT = 5;
      final int MAX_NAVIGATION_PAGE = 10;

      PaginationResult<OrderInfo> paginationResult //
            = orderDAO.listOrderInfo(page, MAX_RESULT, MAX_NAVIGATION_PAGE);

      model.addAttribute("paginationResult", paginationResult);
      return "orderList";
   }


   @RequestMapping(value = { "/admin/product" }, method = RequestMethod.GET)
   public String product(Model model, @RequestParam(value = "code", defaultValue = "") String code) {
      ProductForm productForm = null;

      if (code != null && code.length() > 0) {
         Product product = productDAO.findProduct(code);
         if (product != null) {
            productForm = new ProductForm(product);
         }
      }
      if (productForm == null) {
         productForm = new ProductForm();
         productForm.setNewProduct(true);
      }
      model.addAttribute("productForm", productForm);
      return "product";
   }


   @RequestMapping(value = { "/admin/product" }, method = RequestMethod.POST)
   public String productSave(Model model, //
         @ModelAttribute("productForm") @Validated ProductForm productForm, //
         BindingResult result, //
         final RedirectAttributes redirectAttributes) {

      if (result.hasErrors()) {
         return "product";
      }
      try {
         productDAO.save(productForm);
      } catch (Exception e) {
         Throwable rootCause = ExceptionUtils.getRootCause(e);
         String message = rootCause.getMessage();
         model.addAttribute("errorMessage", message);
         // Show product form.
         return "product";
      }

      return "redirect:/productList";
   }
     @RequestMapping(value = "product/{code}", method = RequestMethod.DELETE)
      public String delete(@PathVariable("code") String code, Model model) {
             Product product = productDAO.findProduct(code);
                 productDAO.delete(product);
                 return "redirect:/productList";
            } 
   @RequestMapping(value = { "/admin/order" }, method = RequestMethod.GET)
   public String orderView(Model model, @RequestParam("orderId") String orderId) {
      OrderInfo orderInfo = null;
      if (orderId != null) {
         orderInfo = this.orderDAO.getOrderInfo(orderId);
      }
      if (orderInfo == null) {
         return "redirect:/admin/orderList";
      }
      List<OrderDetailInfo> details = this.orderDAO.listOrderDetailInfos(orderId);
      orderInfo.setDetails(details);

      model.addAttribute("orderInfo", orderInfo);
      return "order";
   }

}

产品DAO类:

在 ProductDAO 类中,我创建了删除方法。我不知道如何从 DB 方法中编写删除产品。我在 YouTube 上看了一些指南,但找不到解决方案。

    package com.webapp.agroxapp.dao;
    import java.io.IOException;
    import java.util.Date;

     import javax.persistence.NoResultException;
    import org.hibernate.Session;
      import org.hibernate.SessionFactory;
     import org.hibernate.Transaction;
     import org.hibernate.query.Query;
    import com.webapp.agroxapp.entity.Product;
      import com.webapp.agroxapp.form.ProductForm;
      import com.webapp.agroxapp.model.ProductInfo;
       import com.webapp.agroxapp.pagination.PaginationResult;
      import org.springframework.beans.factory.annotation.Autowired;
     import org.springframework.stereotype.Repository;
      import org.springframework.transaction.annotation.Propagation;
      import org.springframework.transaction.annotation.Transactional;

       @Transactional
      @Repository
      public class ProductDAO {

@Autowired
private SessionFactory sessionFactory;

public Product findProduct(String code) {
    try {
        String sql = "Select e from " + Product.class.getName() + " e Where e.code =:code ";

        Session session = this.sessionFactory.getCurrentSession();
        Query<Product> query = session.createQuery(sql, Product.class);
        query.setParameter("code", code);
        return (Product) query.getSingleResult();
    } catch (NoResultException e) {
        return null;
    }
}

public ProductInfo findProductInfo(String code) {
    Product product = this.findProduct(code);
    if (product == null) {
        return null;
    }
    return new ProductInfo(product.getCode(), product.getName(), product.getPrice());
}

@Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public void save(ProductForm productForm) {

    Session session = this.sessionFactory.getCurrentSession();
    String code = productForm.getCode();

    Product product = null;

    boolean isNew = false;
    if (code != null) {
        product = this.findProduct(code);
    }
    if (product == null) {
        isNew = true;
        product = new Product();
        product.setCreateDate(new Date());
    }
    product.setCode(code);
    product.setName(productForm.getName());
    product.setPrice(productForm.getPrice());

    if (productForm.getFileData() != null) {
        byte[] image = null;
        try {
            image = productForm.getFileData().getBytes();
        } catch (IOException e) {
        }
        if (image != null && image.length > 0) {
            product.setImage(image);
        }
    }
    if (isNew) {
        session.persist(product);
    }

    session.flush();
}
       public Product deleteProduct(String code) {  
            return null;    
                   }
public PaginationResult<ProductInfo> queryProducts(int page, int maxResult, int maxNavigationPage,
        String likeName) {
    String sql = "Select new " + ProductInfo.class.getName() //
            + "(p.code, p.name, p.price) " + " from "//
            + Product.class.getName() + " p ";
    if (likeName != null && likeName.length() > 0) {
        sql += " Where lower(p.name) like :likeName ";
    }
    sql += " order by p.createDate desc ";

    Session session = this.sessionFactory.getCurrentSession();
    Query<ProductInfo> query = session.createQuery(sql, ProductInfo.class);

    if (likeName != null && likeName.length() > 0) {
        query.setParameter("likeName", "%" + likeName.toLowerCase() + "%");
    }
    return new PaginationResult<ProductInfo>(query, page, maxResult, maxNavigationPage);
  }

public PaginationResult<ProductInfo> queryProducts(int page, int maxResult, int maxNavigationPage) {
    return queryProducts(page, maxResult, maxNavigationPage, null);
                     }  
                 } 

标签: javaspringhibernatespring-boot

解决方案


删除方法可以是这样的:

public void deleteProduct(String code) {  
Session session = sessionFactory.getCurrentSession();
Query deleteQuery = session.createQuery("DELETE FROM Product p WHERE p.code = :code");
deleteQuery.setParameter("code", code);
deleteQuery.executeUpdate();
}

和控制器方法:

@RequestMapping(value = "product/{code}", method = RequestMethod.DELETE)
public String delete(@PathVariable("code") String code) {
       productDAO.delete(code);
       return "redirect:/productList";
} 

推荐阅读