1

I am making use of Auditing with Spring Data JPA to automatically update the created by time stamp. I have a requirement, where i have to migrate some data for which the created by date should be updated with the value am setting through the application. I have debugged the code, the values are setting properly. But while calling

fooRepository.save(fooEntity)

The created by is getting overridden by the auto generated time stamp. Is it possible to override the value?

I am also having a @Transactional annotation in Service level. While debugging i can see the date is getting replaced on the Entity returned by the save repository method.

Sachin Bose
  • 127
  • 8
  • Are you using `@CreatedDate` then I have a solution? – Eklavya Jun 01 '20 at 14:48
  • 1
    @Eklavya - Yes i am using createdDate for date creation. I guess its something to do with Transactional annotation. Since the entity is under transaction life cycle, it is getting stored only when the entire method is completed. Once the save call is done, the value of creation date is getting replaced with autogenerated date. Once the entire method is computed, when the actual save happens, it is saving the autogenerated value. – Sachin Bose Jun 02 '20 at 09:08

2 Answers2

1

It is not a better way but you can follow. First, create the entity

fooRepository.saveAndFlush(fooEntity);

and then update the createdAt data then save the entity again.

fooEntity.setCreatedAt(yourTime);
fooRepository.saveAndFlush(fooEntity);
Eklavya
  • 17,618
  • 4
  • 28
  • 57
  • Like i mentioned in my question, since am using a @Transactional on top of the method. The entity is getting persisted only once the entire methods is completed. It is not getting persisted each time i make a save repository call. – Sachin Bose Jun 03 '20 at 10:05
  • @SachinBose Did you check ?, cause persist won't work when creating an entity I think – Eklavya Jun 03 '20 at 10:14
  • Can you try `saveAndFlush(fooEntity)` ? It should work see here https://stackoverflow.com/questions/49855138/transactional-annotation-works-with-saveandflush – Eklavya Jun 03 '20 at 19:19
0

Create new enity without @CreatedDate and new repository for that new entity.

Only use that new repository when you need to edit CreatedDate or LastModifiedDate

This seems to be a bad solution but is the only solution I can think of now.

I am looking for better solution to this problem

Do Trung Duc
  • 396
  • 3
  • 13