Spring数据jpa保存无法获取id

时间:2013-05-03 03:34:27

标签: jpa spring-mvc spring-data spring-data-jpa

生成我的实体ID,当我使用DAO而不是Spring数据JPA时,它工作正常。

@Id
@Column(name = TABLE_COLUM_NAME_ID)
@GeneratedValue
private int id;

现在我已经开始使用Spring数据JPA,在我致电repository.save(myboject)repository.saveAndFlush(myobject)后,我致电myobject.getId()。但是id永远不会填充。

我搜索了我的数据库,对象在数据库中,ID正确。 我打电话给save()之后有谁知道为什么没有设置id?我使用entitymanager.save()时没有问题。

7 个答案:

答案 0 :(得分:14)

我相信这篇文章回答了你的问题:

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

repository.save()方法实际上返回一个新对象,如JPA entityManager.merge(),返回的对象是将设置ID的对象。

答案 1 :(得分:11)

试试这个

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

然后致电getId();

答案 2 :(得分:7)

  1. 您应该使用repository.saveAndFlush();方法:
  2.   

    MyObject savedObject= repository.saveAndFlush(newObject);

    1. 在实体对象描述中,您应将以下属性(@GeneratedValue(strategy = GenerationType.AUTO))添加到相关字段(id):
    2. @Id   
      @Column(name = "id")   
      @GeneratedValue(strategy = GenerationType.AUTO)   
      public long getId() {  
          return id;  
      }
      

答案 3 :(得分:6)

尝试为@GeneratedValue指定策略

@GeneratedValue(strategy = GenerationType.AUTO)

答案 4 :(得分:3)

此方法返回已保存的id

myobject = repository.saveAndFlush(myobject);

现在你有id

答案 5 :(得分:0)

我终于明白了。即使save方法无效,您也可以为其设置一个变量。(?)

    @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";
}

答案 6 :(得分:0)

我猜您在Service方法上没有@Transactional注释。