Spring data jpa save can not get id

前端 未结 7 1284
隐瞒了意图╮
隐瞒了意图╮ 2020-12-10 01:09

My entity id is generated, and it was working fine when I use DAO instead of Spring data JPA.

@Id
@Column(name = TABLE_COLUM_NAME_ID)
@GeneratedValue
private         


        
相关标签:
7条回答
  • 2020-12-10 01:22

    I finally figured it out. Even though the save method is void, you can set a variable to it.(?)

        @PostMapping(value = "customer/{id}/wish/add")
    public String processAddWish(Model model, @PathVariable int id,
                                 @ModelAttribute @Valid WishOrder newWishOrder,
                                 Errors errors) {
        if (errors.hasErrors()) {
            return "customer/wish/add";
        }
        //Initialize variable to the save method, even though it is void and returns nothing//
        //Eliminates need to access object through a .findById//
        //If you need the id of the saved object instantly, just add .getId to save call//
        //wishOrderDao.save(newWishOrder).getId()//
        WishOrder wish = wishOrderDao.save(newWishOrder);
        Customer customer = customerDao.findById(id);
        customer.getWishList().add(wish);
        customerDao.save(customer);
    
        model.addAttribute("customer",(customer));
        model.addAttribute("wishList", (customer.getWishList()));
    
        return "customer/wishList";
    }
    
    0 讨论(0)
  • 2020-12-10 01:23

    This method returns the saved id

    myobject = repository.saveAndFlush(myobject);
    

    Now you have your id.

    0 讨论(0)
  • 2020-12-10 01:27

    I guess you didn't have a @Transactional annotation on your Service method.

    0 讨论(0)
  • 2020-12-10 01:32

    Try specifying strategy for @GeneratedValue like

    @GeneratedValue(strategy = GenerationType.AUTO)
    
    0 讨论(0)
  • 2020-12-10 01:33

    I believe this post answers your question:

    Why to use returned instance after save() on Spring Data JPA Repository?

    The repository.save() method actually returns a new object like JPA entityManager.merge() and the returned object is the one that will have the ID set.

    0 讨论(0)
  • 2020-12-10 01:36

    Try this like

    myboject = repository.save(myboject);
    repository.flush();
    

    Then after call to getId();

    0 讨论(0)
提交回复
热议问题