【问题标题】:Spring Data JPA Merge Updated EntitySpring Data JPA 合并更新的实体
【发布时间】:2015-08-15 02:54:00
【问题描述】:

我尝试使用 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 new 实体。应该说 3 带有更新的属性。

【问题讨论】:

  • 好吧,我做了一些测试,似乎在更新实体的 POST 方法上,订单对象返回了一个空 ID。我不知道为什么模型属性会出现在表单中,我使用了@ModelAttribute 注解。

标签: java spring jpa


【解决方案1】:

您需要将实体存储在 GET 请求和 POST 请求之间的某个位置。您的选择:

  1. 在 POST 开始时从数据库中重新加载实体并从 POST 实体中复制其属性
  2. 将实体信息存储在隐藏的表单变量中
  3. 将实体存储在会话中

3 是唯一正确的解决方案,因为它允许乐观并发控制,并且比隐藏表单变量更安全。

在控制器顶部添加@SessionAttributes("modelAttributeName"),并将SessionStatus 参数添加到您的POST 处理程序方法。完成后致电sessionStatus.setComplete()。有关工作示例,请参阅Spring MVC: Validation, Post-Redirect-Get, Partial Updates, Optimistic Concurrency, Field Security

【讨论】:

  • 你只对 API 使用“method=RequestMethod.PUT”吗?因为我注意到 JSP 和 Spring 表单标签不支持“PUT”。所以我猜你仍然在“更新”方法上使用 POST .. 实际更新发生在数据层。另外,您是否必须在您的实体上使用@Version?
  • 实际上是网络浏览器不会从 html 表单中放入/删除,而不仅仅是 spring。不过可以使用 put/delete w Ajax。您只需要 @version 进行乐观锁定
猜你喜欢
  • 1970-01-01
  • 2012-08-06
  • 2020-08-19
  • 2019-06-15
  • 1970-01-01
  • 1970-01-01
  • 2019-09-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多