英文:
Set datetime field now in MapStruct?
问题
我有一个POJO类中的Instant字段,希望在创建记录时将其值设置为 `now()`。据我所见,MapStruct支持这种功能,但我无法正确设置它:
***mapper:***
@Mapper(componentModel = "spring", imports = {Instant.class})
public interface CreatePostRequestMapper {
// @Mapping(target = "createdAt", defaultExpression ="java(Instant.now())")
@Mapping(target = "createdAt", defaultValue = "java(Instant.now())")
Post toEntity(CreatePostRequest source);
CreatePostRequest toDto(Post destination);
}
并且两个类都具有相同名称的相同属性:
private Instant createdAt;
以下是服务方法:
private final CreatePostRequestMapper createPostRequestMapper;
public PostDetails createPost(@Valid CreatePostRequest request) {
final Post post = createPostRequestMapper.toEntity(request);
// 省略的代码
}
这将导致以下错误:
"Request processing failed; nested exception is java.time.format.DateTimeParseException: Text 'java(Instant.now())' could not be parsed at index 0] with root cause"
如何解决这个问题?
英文:
I have an Instant field in my POJO class and want to set its value now()
while creating record. As far as I see, MapStruct let this kind of feature, but I could not set it properly:
mapper:
@Mapper(componentModel = "spring", imports = {Instant.class})
public interface CreatePostRequestMapper {
// @Mapping(target = "createdAt", defaultExpression ="java(Instant.now())")
@Mapping(target = "createdAt", defaultValue = "java(Instant.now())")
Post toEntity(CreatePostRequest source);
CreatePostRequest toDto(Post destination);
}
And both classes has the same property with the same name:
private Instant createdAt;
Here is the service method:
private final CreatePostRequestMapper createPostRequestMapper;
public PostDetails createPost(@Valid CreatePostRequest request) {
final Post post = createPostRequestMapper.toEntity(request);
// code omitted
}
This gives the following error:
"Request processing failed; nested exception is java.time.format.DateTimeParseException: Text 'java(Instant.now())' could not be parsed at index 0] with root cause"
How can solve this?
答案1
得分: 0
当您在Instant类中使用defaultValue时,它将生成以下代码:
post.setCreatedAt( Instant.parse( "java(Instant.now())" ) );
显然,Instant类无法解析这个字符串并创建一个对象。
所以,正确的方式是使用defaultExpression,这将生成以下代码:
post.setCreatedAt( Instant.now() );
区别是显而易见的
希望这对您有所帮助。
英文:
When you use defaultValue for Instant class, it will generate following code:
post.setCreatedAt( Instant.parse( "java(Instant.now())" ) );
And, obviously, Instant class cannot parse this string and create an object.
So, the right way is to use defaultExpression, this will generate following code:
post.setCreatedAt( Instant.now() );
The difference is noticeable
Hope it will help you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论