Sumit
Sumit

Reputation: 103

Getting null id after calling save, only after using @transactional in spring boot project

`

@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;`

not able to get the saved Id of user only after using transactional annotation else getting the id after removing transactional annotation . Any help would be appreciable.

Upvotes: 1

Views: 3304

Answers (1)

Alan Hay
Alan Hay

Reputation: 23246

Change as below:

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

Typically database updates will not be flushed until your @Transactional method returns. By using saveAndFlush(e) (which delegates to EntityManager#flush - What does EntityManager.flush do and why do I need to use it?) you can force the database update to happen immediately.

As an aside, for or a newly persistent entity the save(e) or saveAndFlush(e) method calls simply return e so no need to assign the returned result to another variable.

Upvotes: 5

Related Questions