I looked for countless questions.
But most of the questions were as follows.
- Entity -> Dto
- Entity and Dto have the same attribute value.
but I don't want this.
I wonder how I can convert Dto to Entity when if property value present in Entity did not exist in Dto.
Some Code
dosen't specify the codes for the [annotations, Lombok, jpa, ...etc]
but it exists!
User Entity
class User {
Long id,
String username,
String email,
String password
}
UserDto
class UserDto {
String email
}
Post Entity
class Post {
Long id,
String title,
User user
}
PostDto
class PostDto {
Long id,
String title,
String username
}
UserService
...
UserDto findUser(id: Long) {
...
}
...
PostService
...
PostDto savePost(Post post) {
...
}
...
PostController
...
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)
}
...
Question
All methods of userService return in DTO.
how can I set user entity in Post Entity?
I received a userDto return which has only username.
What should I do at times like this?
- The repository is not being called directly from the controller.
- The service would like to return the DTO unconditionally.
- Should I create an additional Dto that has the same properties as user entity?
question from:
https://stackoverflow.com/questions/65895506/how-can-convert-dto-to-entity-in-spring-boot 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…