【问题标题】:Getting AutoIncrement value after saving in Spring在 Spring 中保存后获取 AutoIncrement 值
【发布时间】:2019-03-17 13:00:48
【问题描述】:

我正在使用 Spring Boot 2(Hibernate、JPA)和 MySQL。我需要一个唯一的、自动递增的自定义参考编号,例如 18/10/5(这里,18 是年,10 是月,5 是自动递增字段)。我使用的策略是:

创建一个自动递增字段。保存并加入yy/MM/后获取自增的值。

为方便起见,我删除了不需要的注释。

模型类

@Entity
@Table(name="account")
public class Account{
    @Id
    private String id;
    
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long autoIncrement;
    
    String refNo;
    
    //Other fields, Constructors, Getters And Setters
}

然后在控制器中,首先我保存,然后我获取保存对象的 id 并尝试更新

控制器类

@RestController
@RequestMapping("/account")
public class AccountController {

    @PostMapping("/save")
    public ModelAndView saveAccount(@ModelAttribute("account") Account account){
        //few codes
        accountService.save(account) //Saving
        
        accountService.updateRefNo(account.getId()) //try to update
    }
}

服务类

@Service
@Transactional
public class AccountServiceImpl implements AccountService{

    @Autowired
    AccountRepository accountRepository;
    
    //Few methods
    
    public void updateRefNo(String id) {        
        Account account=findById(id); // return the object
        
        String year = // getting year
        String month = //getting month
        
        account.setRefNo(year+"/"+month+"/"+account.getAutoIncrement());
    }
}

数据已保存。当我尝试更新时,account.getAutoIncrement() 返回 null,但它保存在数据库中。我也试过saveAndFlush()。为什么会这样?没有承诺?

【问题讨论】:

  • 该帐户是新帐户吗?并且是客户提供的帐户ID吗?我通常看到的代码在保存时会生成 id。如果您的代码也是如此,您不使用 null 调用您的 updateRefNo 方法,因为您不使用保存返回的 id 吗?

标签: mysql spring hibernate spring-boot spring-data-jpa


【解决方案1】:

在您的 updateRefNo 中,我没有看到对 Account 实体的保存或更新调用

public void updateRefNo(String id) {        
    Account account=findById(id); // return the object

    String year = // getting year
    String month = //getting month

    account.setRefNo(year+"/"+month+"/"+account.getAutoIncrement());

    // update in DB
    accountRepository.save(account);  or accountRepository.update(account);
}

【讨论】:

  • 由于我使用@Transactional,希望不需要创建新的调用/方法
  • @Transaction 与保存/更新有什么关系。它有不同的目的??您可以添加您的 accountService.save 方法吗?我想看看你是如何保存细节的
  • 只保存方法accountRepository.save(account)。我看了一些教程,如果我们使用@Transactional,我们不需要指定任何方法,这个注解总是与db进行事务,所以不需要调用任何方法。,这是第二个问题,但首先是@987654327 @ 返回 null 的 account.getAutoIncrement()
  • @MyTwoCents @Transactional 不需要任何特定的方法来保存或更新。自动保存。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-13
  • 1970-01-01
  • 1970-01-01
  • 2019-12-03
  • 2018-01-11
  • 2010-10-18
  • 1970-01-01
相关资源
最近更新 更多