Closed bwgjoseph closed 2 years ago
Yes, it is expected that you have an instance of the subdocument. Spring Data cannot fill in auditing values into a property that is null
. We also cannot reason whether to create or not create object instances because the data is yours, not ours.
In that case, if I define the document as
@Builder
@ToString
public class AuditMetadata {
@CreatedBy
private String createdBy;
@CreatedDate
private LocalDateTime createdDateTime;
}
Which I expect Spring
to help filled up all the fields. In that case, I have to create an empty object for this to work?
@Test
void test() {
Customer p = Customer.builder().name("Shane").auditMetadata(AuditMetadata.builder().build()).build();
Customer saved = personRepository.insert(p);
}
That seem to be too verbose.
Is there any way to do this to tell Spring?
public class Customer {
@Id
private String id;
private String name;
@EmbeddedAuditMetadata
private AuditMetadata auditMetadata;
}
And it can init the class, and set the values accordingly?
Thanks
In that case, I have to create an empty object for this to work?
Yes, you need to create that object. We cannot reason about whether to create a subdocument or not because presence of subdocuments is subject to your application.
Based on the docs for auditing, it states that
I tested it out, but it doesn't seem to work as described. Otherwise, it could be my interpretation is wrong of how it should work
So I have this simple configuration setup to test
And I tested with both type; root based, and embedded based
Root based
Given this entity
If I run a test with the following
The output of
saved
isSo this works as expected, but if I were to switch to use the embedded one, then
createdBy
wouldn't be populated at allEmbedded based
For this, I made some small adjustment to the class
With the same test, the output is
So I tried out something which is to set the timestamp myself, just to initialize the class, and to see if that will work, and it did. I tweaked the test a little to
To ensure that the object is not null to begin with. And the output was
Notice that the name is now filled up automatically. I just had to ensure the object is not null for
Spring
to fill up the@CreatedBy
field.So my question is, is this behavior expected? If it does, then I think the documentations may have to be more explicit, if it's not, then what I do wrong? And documentations may have to be more explicit as well
Thanks!