Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java Spring数据JPA合并更新实体_Java_Spring_Jpa - Fatal编程技术网

Java Spring数据JPA合并更新实体

Java Spring数据JPA合并更新实体,java,spring,jpa,Java,Spring,Jpa,我已经尝试了很长一段时间使用SpringBoot+SpringDataJPA更新实体。我得到了所有正确的意见。我的编辑视图按ID向我返回正确的实体。一切都进展顺利。。直到我真正尝试保存/合并/持久化对象每次我都会得到一个带有新ID的新实体。我只是不知道为什么。我已经看了网上的例子,还有你可能会提到我的重复问题的链接。那么我在这些代码中哪里犯了错误呢 package demo; import javax.persistence.Column; import javax.p

我已经尝试了很长一段时间使用SpringBoot+SpringDataJPA更新实体。我得到了所有正确的意见。我的编辑视图按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();
        }

    }
import java.util.List;
导入org.springframework.beans.factory.annotation.Autowired;
导入org.springframework.stereotype.Controller;
导入org.springframework.validation.BindingResult;
导入org.springframework.web.bind.annotation.ModelAttribute;
导入org.springframework.web.bind.annotation.PathVariable;
导入org.springframework.web.bind.annotation.RequestMapping;
导入org.springframework.web.bind.annotation.RequestMethod;
导入org.springframework.web.servlet.ModelAndView;
导入org.springframework.web.servlet.mvc.support.RedirectAttributes;
@控制器
公共类OrderController{
//重构以服务于
//日志功能
@自动连线
orderRepo;
@自动连线
CustomJpaService CustomJpaService;
@RequestMapping(value=“/orders”,method=RequestMethod.GET)
公共模型和视图列表订单(){
List orders=orderepo.findAll();
返回新模型和视图(“订单”、“订单”、订单);
}
@RequestMapping(value=“/orders/{id}”,method=RequestMethod.GET)
公共模型和视图显示顺序(@PathVariable整数id,顺序){
order=orderepo.findOne(id);
返回新模型和视图(“showOrder”、“order”、“order”);
}
@RequestMapping(value=“/orders/edit/{id}”,method=RequestMethod.GET)
公共模型和视图编辑表单(@PathVariable(“id”)整数id){
订单=orderepo.findOne(id);
返回新模型和视图(“编辑订单”、“订单”、“订单”);
}
@RequestMapping(value=“/updateorder”,method=RequestMethod.POST)
公共字符串更新顺序(@modeldattribute(“order”)顺序,BindingResult BindingResult,final RedirectAttributes RedirectAttributes){
if(bindingResult.hasErrors()){
返回“重定向:/orders/edit/”+order.getId();
}
customJpaService.saveOrUpdateOrder(订单);
redirectattributes.addFlashAttribute(“successAddNewOrderMessage”,“订单更新成功!”);
返回“重定向:/orders/”+order.getId();
}
@RequestMapping(value=“/orders/new”,method=RequestMethod.GET)
公共模型和视图订单(){
返回新的ModelAndView(“newOrder”、“order”、newOrder());
}
@RequestMapping(value=“/orders/new”,method=RequestMethod.POST)
公共字符串addOrder(订单顺序、最终重定向属性){
orderepo.save(订单);
redirectAttributes.addFlashAttribute(“successAddNewOrderMessage”,“Success!Order”+Order.getName()+“added successfully!”);
返回“重定向:/orders/”+order.getId();
}
}

在这个代码之后。我的视图将我返回到正确的URL,但ID为4时,需要将实体存储在GET请求和POST请求之间的某个位置。您的选择:

  • 在发布开始时从数据库重新加载实体,并从发布的实体复制其属性
  • 将实体信息存储在隐藏的表单变量中
  • 将实体存储在会话中
  • 3是唯一正确的解决方案,因为它允许乐观并发控制,并且比隐藏的表单变量更安全


    在控制器顶部添加
    @SessionAttributes(“modelAttributeName”)
    ,并在POST处理程序方法中添加
    SessionStatus
    参数。完成后调用sessionStatus.setComplete()。有关工作示例,请参见

    我做了一些测试,似乎在更新实体的POST方法上,order对象返回的ID为null。我不知道为什么表单中会出现模型属性,我使用了@modeldattribute注释。您是否只使用“method=RequestMethod.PUT”作为API?因为我注意到JSP和Spring表单标记不支持“PUT”。所以我猜你仍然使用POST的“更新”方法。。实际更新发生在数据层。另外,你必须在你的实体上使用@Version吗?事实上,web浏览器不从html表单中进行放/删除,而不仅仅是spring。但是可以使用put/deletewajax。乐观锁定只需要@version