Spring数据jpa保存无法获取id

Spring数据jpa保存无法获取id,jpa,spring-mvc,spring-data,spring-data-jpa,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是正确

我的实体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()时,我没有任何问题。

像这样尝试一下

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

然后在调用
getId()
之后

尝试为
@GeneratedValue
指定策略

@GeneratedValue(strategy = GenerationType.AUTO)

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


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

此方法返回保存的
ID

myobject = repository.saveAndFlush(myobject);
现在您有了
id

  • 您应该使用
    repository.saveAndFlush()方法:
  • MyObject savedObject=repository.saveAndFlush(newObject)

  • 在实体对象描述中,应将以下属性(
    @GeneratedValue(strategy=GenerationType.AUTO)
    )添加到相关字段(
    id
    ):

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


    我猜您的服务方法上没有@Transactional注释。

    问题在于MyEntity requestEntity;savedEntity=repositroy.save(requestEntity)。Id不在requestEntity中,但在savedEntity@NPKR请不要给出这样的答案,试试这个。。。在需要时添加适当的解释以回答问题。不需要这样做,您只需在实体中添加以下注释:@Id@GeneratedValue(strategy=GenerationType.IDENTITY)@Column(name=“Id”)private long Id;AUTO是默认值:这对我有用,谢谢,缺少generateValue注释
    @Id   
    @Column(name = "id")   
    @GeneratedValue(strategy = GenerationType.AUTO)   
    public long getId() {  
        return id;  
    }
    
        @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";
    }