【发布时间】:2021-01-26 03:29:24
【问题描述】:
我寻找了无数的问题。 但大部分问题如下。
- 实体 -> Dto
- Entity 和 Dto 具有相同的属性值。
但我不想要这个。
我想知道如果实体中存在的属性值在 Dto 中不存在,我如何将 Dto 转换为实体。
一些代码
不指定 [annotations, Lombok, jpa, ...etc] 的代码 但它存在!
用户实体
class User {
Long id,
String username,
String email,
String password
}
UserDto
class UserDto {
String email
}
发布实体
class Post {
Long id,
String title,
User user
}
PostDto
class PostDto {
Long id,
String title,
String username
}
用户服务
...
UserDto findUser(id: Long) {
...
}
...
邮政服务
...
PostDto savePost(Post post) {
...
}
...
后控制器
...
PostDto createPost(@RequestBody PostDto postDto) {
// spring security
Long userId = XXX.getUserId()
....
UserDto userDto = userService.findUser(userId)
// HERE !! what can i do ??
// How can i convert userDto to user ?
Post post = new Post(postDto.title, user)
PostDto newPost = postService.savePost(post)
}
...
问题
userService 的所有方法都在 DTO 中返回。 如何在 Post Entity 中设置用户实体? 我收到了一个 userDto 返回,它只有用户名。
这种时候我该怎么办?
- 没有直接从控制器调用存储库。
- 服务希望无条件返回 DTO。
- 是否应该创建一个与用户实体具有相同属性的附加 Dto?
【问题讨论】:
-
我建议查看 MapStruct。
-
感谢您的评论。我使用了 MapStruct。
标签: java spring spring-boot entity dto