java - Spring Data JPA 合并更新的实体

标签 java spring jpa

我尝试使用 Spring Boot + Spring Data JPA 更新实体已经有一段时间了。我得到了所有正确的观点。我的编辑 View 通过 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();
        }

    }

在这段代码之后。我的 View 将我返回到正确的 URL,但 ID 为 4 <-- 这是一个实体。它应该说 3 具有更新的属性。

最佳答案

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

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

3 是最简单的解决方案,因为它允许乐观的并发控制,并且比隐藏形式的变量更安全。

如果你对隐藏的表单变量进行 HMAC 并检查它是否正确,2 会很好

在您的 Controller 顶部添加 @SessionAttributes("modelAttributeName"),并将 SessionStatus 参数添加到您的 POST 处理程序方法。完成后调用 sessionStatus.setComplete()。参见 Spring MVC: Validation, Post-Redirect-Get, Partial Updates, Optimistic Concurrency, Field Security一个工作示例。

关于java - Spring Data JPA 合并更新的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32021049/

相关文章:

Java可迭代: why is iterator for one object iterates over data from another?

java - Apache Beam - BigQueryIO 读取投影

spring - 错误:org.hibernate.hql.internal.ast.QuerySyntaxException,请帮助我?

java - 尝试使用 Autowiring 的候选者运行存储库 impl 进行测试

java - Entitymanager.persist 在 Informix UDR 中失败

java - session 范围 Bean 不是 session 范围 Bean

Java - 如何显示独立于货币区域设置的多种货币?

java - Spring Rest 模板 - 将请求字符串主体发布到 azure 给出 500 错误

java - 在 Spring 中使用 JPA 在 Oracle 上重复读取

java - Hibernate @OneToOne 自连接,在连接子句中使用 OR