Spring Data JPA合并已更新实体

3

我已经尝试了相当长的时间来使用Spring Boot + Spring Data JPA更新实体。我得到了所有正确的视图返回给我。我的编辑视图按ID将正确的实体返回给我。一切都很顺利......直到我实际尝试保存/合并/持久化对象。 每次我都会得到一个新的带有新ID的实体。我不知道为什么。我已经查看了在线示例以及您可能要引用的重复问题的链接。那么在这些代码片段中,我犯了什么错误呢?

    package demo;

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.Table;

    @Entity
    @Table(name = "ORDERS")
    public class Order {

        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Integer id;

        @Column(name = "ORDER_NAME")
        private String name;

        @Column(name = "ORDER_DESCRIPTION")
        private String description;

        @Column(name = "ORDER_CONTENT")
        private String content;

        public Order() {}

        public Order(String name, String description, String content) {
            this.name = name;
            this.description = description;
            this.content = content;
        }

        public String getContent() {
            return content;
        }

        public String getDescription() {
            return description;
        }

        public String getName() {
            return name;
        }

        public Integer getId() {
            return this.id;
        }

        public void setContent(String content) {
            this.content = content;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Order other = (Order) obj;
            if (content == null) {
                if (other.content != null)
                    return false;
            } else if (!content.equals(other.content))
                return false;
            if (description == null) {
                if (other.description != null)
                    return false;
            } else if (!description.equals(other.description))
                return false;
            if (id == null) {
                if (other.id != null)
                    return false;
            } else if (!id.equals(other.id))
                return false;
            if (name == null) {
                if (other.name != null)
                    return false;
            } else if (!name.equals(other.name))
                return false;
            return true;
        }

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((content == null) ? 0 : content.hashCode());
            result = prime * result
                    + ((description == null) ? 0 : description.hashCode());
            result = prime * result + ((id == null) ? 0 : id.hashCode());
            result = prime * result + ((name == null) ? 0 : name.hashCode());
            return result;
        }

        @Override
        public String toString() {
            return "Order [id=" + id + ", name=" + name + ", description="
                    + description + ", content=" + content + "]";
        }

    }





    package demo;

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

    public interface OrderRepository extends JpaRepository<Order, Integer> {

        public Order findByName(String name);


    }

包演示;

    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.transaction.Transactional;

    import org.springframework.stereotype.Service;

    @Service("customJpaService")
    public class CustomJpaServiceImpl implements CustomJpaService{

        @PersistenceContext
        private EntityManager em;

        @Transactional
        public Order saveOrUpdateOrder(Order order) {

            if (order.getId() == null) {
                em.persist(order);
            } else {
                em.merge(order);
            }
            return order;
        }

    }

包演示;

    import java.util.List;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.validation.BindingResult;
    import org.springframework.web.bind.annotation.ModelAttribute;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.mvc.support.RedirectAttributes;

    @Controller
    public class OrderController {

        //refactor to service with 
        //logging features
        @Autowired
        OrderRepository orderRepo;

        @Autowired
        CustomJpaService customJpaService;

        @RequestMapping(value="/orders", method=RequestMethod.GET)
        public ModelAndView listOrders() {

            List<Order> orders = orderRepo.findAll();

            return new ModelAndView("orders", "orders", orders);

        }

        @RequestMapping(value="/orders/{id}", method=RequestMethod.GET)
        public ModelAndView showOrder(@PathVariable Integer id, Order order) {
            order = orderRepo.findOne(id);
            return new ModelAndView("showOrder", "order", order);
        }

        @RequestMapping(value="/orders/edit/{id}", method=RequestMethod.GET)
        public ModelAndView editForm(@PathVariable("id") Integer id) {
            Order order = orderRepo.findOne(id);
            return new ModelAndView("editOrder", "order", order);
        }

        @RequestMapping(value="/updateorder", method=RequestMethod.POST)
        public String updateOrder(@ModelAttribute("order") Order order, BindingResult bindingResult, final RedirectAttributes redirectattributes) {

            if (bindingResult.hasErrors()) {
                return "redirect:/orders/edit/" + order.getId();
            }

            customJpaService.saveOrUpdateOrder(order);
            redirectattributes.addFlashAttribute("successAddNewOrderMessage", "Order updated successfully!");
            return "redirect:/orders/" + order.getId();
        }


        @RequestMapping(value="/orders/new", method=RequestMethod.GET)
        public ModelAndView orderForm() {
            return new ModelAndView("newOrder", "order", new Order());
        }

        @RequestMapping(value="/orders/new", method=RequestMethod.POST)
        public String addOrder(Order order, final RedirectAttributes redirectAttributes) {
            orderRepo.save(order);
            redirectAttributes.addFlashAttribute("successAddNewOrderMessage", "Success! Order " + order.getName() + " added successfully!");
            return "redirect:/orders/" + order.getId();
        }

    }

在这段代码后,我的视图将我带回适当的URL,但ID为4 <-- 这是一个实体。它应该显示更新了属性的3。


我进行了一些测试,似乎在更新实体的POST方法中,订单对象返回了一个空的ID。我不知道为什么模型属性存在于表单中,我使用了@ModelAttribute注释。 - DtechNet
1个回答

3
您需要在GET请求和POST请求之间的某个地方存储实体。以下是您的选项:
  1. 在POST开头重新加载实体,并从POST的实体中复制其属性
  2. 将实体信息存储在隐藏表单变量中
  3. 将实体存储在会话中
第三种方法是最简单的解决方案,因为它允许进行乐观并发控制,而且比隐藏表单变量更安全。
如果对隐藏表单变量进行HMAC并检查其是否正确,则可以选择第二种方法。
在您的控制器顶部添加@SessionAttributes("modelAttributeName"),并在您的POST处理程序方法中添加一个SessionStatus参数。完成后调用sessionStatus.setComplete()。请参阅Spring MVC:验证、Post-Redirect-Get、部分更新、乐观并发、字段安全性以获取可行示例。

你在API中只使用“method = RequestMethod.PUT”吗?因为我注意到JSP和Spring表单标记不支持“PUT”。所以我猜您仍然会在“update”方法上使用POST..实际的更新发生在数据层。此外,您是否必须在实体上使用@Version? - DtechNet
实际上,不仅是Spring,Web浏览器也不能将/删除HTML表单。但可以使用Ajax进行put/delete操作。您只需要在乐观锁定时使用@version即可。 - Neil McGuigan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接