【问题标题】:Getting null id after calling save, only after using @transactional in spring boot project调用保存后获取null id,仅在spring boot项目中使用@transactional后
【发布时间】:2019-12-03 00:03:34
【问题描述】:

`

@Service
@Transactional

Public class UserService

public void saveUser()
    User userEntity = new User();
    userEntity.setName("test");
    User userDataFromDB =            userRepository.save(userEntity);
    LOG.info("user Id= " +userDataFromDB.getId());

//entity code below
@Id 
@GeneratedValue(strategy = 
GenerationType.IDENTITY)

@Column(name="ID")
private int id;

@Column(name="NAME")
private string name;`

只有在使用事务注释后才能获取保存的用户 ID,否则在删除事务注释后获取 id。任何帮助都将不胜感激。

【问题讨论】:

  • 请发布您的完整代码,而不仅仅是一个小sn-p。
  • 从我的手机发布,这就是为什么我能够只编写代码 sn-p。

标签: spring-boot jpa spring-data-jpa spring-transactions


【解决方案1】:

修改如下:

public void saveUser()
    User userEntity = new User();
    userEntity.setName("test");
    userRepository.saveAndFlush(userEntity); //force immediate db write
    LOG.info("user Id= " + userEntity.getId());
}

在您的@Transactional 方法返回之前,通常不会刷新数据库更新。通过使用saveAndFlush(e)(委托给EntityManager#flush - What does EntityManager.flush do and why do I need to use it?) 你可以强制数据库更新立即发生。

顺便说一句,对于新的持久实体,save(e)saveAndFlush(e) 方法调用只需返回 e,因此无需将返回的结果分配给另一个变量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-03
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 2019-03-17
    • 1970-01-01
    相关资源
    最近更新 更多