保存后自动增值-spring

r7knjye2  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(362)

我和你一起工作 spring boot 2 (hibernate,jpa) and mysql . 我需要一个唯一的,自动递增的自定义参考编号。 Eg :**18/10/5**(Here, 18 -is year, 10- is month, 5 - auto increment field). 我用的策略是,
创建自动递增字段。保存并加入后得到自动递增的值 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() 也。为什么会这样(没有承诺?)任何人谁知道任何解决办法,请让我知道。提前谢谢。

cbjzeqam

cbjzeqam1#

在你的 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);
}

相关问题