spring 实体:return 创建记录的 ID
spring entity : return id of created record
我有这个AccountantRepository
class
@Repository("accountantRepository")
@Transactional
public interface AccountantRepository extends JpaRepository<Accountant, Long>
在AccountantServiceImpl
@Service("accountantService")
public class AccountantServiceImpl implements AccountantService{
@Autowired
private AccountantRepository accountantRepository;
@Override
public Accountant saveAccountant(Accountant newAccountant, String role) {
return accountantRepository.save(newAccountant);
}
}
当我这样做时accountantRepository.save(newAccountant);
如何获取新建记录的id?
使用 JpaRepository.save()
返回的实例。它将包含 id
值。
CrudRepository.save()
方法(其中声明了 save()
)指定:
Use the returned instance for further operations as the save operation
might have changed the entity instance completely.
您可以直接从实体本身获取 id。 newAccountant.getId()
(或任何字段)将 return 调用保存方法后的数据。
如下图-
@Override
public int saveAccountant(Accountant newAccountant, String role) {
accountantRepository.save(newAccountant);
return newAccountant.getId();
}
此引用将在休眠会话中可用,并且休眠会将 ID 设置为持久对象。
我有这个AccountantRepository
class
@Repository("accountantRepository")
@Transactional
public interface AccountantRepository extends JpaRepository<Accountant, Long>
在AccountantServiceImpl
@Service("accountantService")
public class AccountantServiceImpl implements AccountantService{
@Autowired
private AccountantRepository accountantRepository;
@Override
public Accountant saveAccountant(Accountant newAccountant, String role) {
return accountantRepository.save(newAccountant);
}
}
当我这样做时accountantRepository.save(newAccountant);
如何获取新建记录的id?
使用 JpaRepository.save()
返回的实例。它将包含 id
值。
CrudRepository.save()
方法(其中声明了 save()
)指定:
Use the returned instance for further operations as the save operation might have changed the entity instance completely.
您可以直接从实体本身获取 id。 newAccountant.getId()
(或任何字段)将 return 调用保存方法后的数据。
如下图-
@Override
public int saveAccountant(Accountant newAccountant, String role) {
accountantRepository.save(newAccountant);
return newAccountant.getId();
}
此引用将在休眠会话中可用,并且休眠会将 ID 设置为持久对象。