Spring data jpa save can not get id

2020-02-05 11:46发布

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 int id;

Now I have starting to use Spring data JPA, and after I call repository.save(myboject), or repository.saveAndFlush(myobject), I call myobject.getId(). But the id is never populated.

I searched my database and the object is in the database and the id is correct. Does anyone know why the id is not set after i called save()? I have no issue when I use entitymanager.save().

6条回答
家丑人穷心不美
2楼-- · 2020-02-05 12:10

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";
}
查看更多
趁早两清
3楼-- · 2020-02-05 12:12
  1. You should use the repository.saveAndFlush(); method:

MyObject savedObject= repository.saveAndFlush(newObject);

  1. In the Entity object description, you should add the following attribute(@GeneratedValue(strategy = GenerationType.AUTO)) to the related field(id):
@Id   
@Column(name = "id")   
@GeneratedValue(strategy = GenerationType.AUTO)   
public long getId() {  
    return id;  
}
查看更多
forever°为你锁心
4楼-- · 2020-02-05 12:28

Try specifying strategy for @GeneratedValue like

@GeneratedValue(strategy = GenerationType.AUTO)
查看更多
等我变得足够好
5楼-- · 2020-02-05 12:29

Try this like

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

Then after call to getId();

查看更多
一纸荒年 Trace。
6楼-- · 2020-02-05 12:29

This method returns the saved id

myobject = repository.saveAndFlush(myobject);

Now you have your id.

查看更多
\"骚年 ilove
7楼-- · 2020-02-05 12: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.

查看更多
登录 后发表回答