I looked for countless questions. But most of the questions were as follows.
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.
dosen't specify the codes for the [annotations, Lombok, jpa, ...etc] but it exists!
class User {
Long id,
String username,
String email,
String password
}
class UserDto {
String email
}
class Post {
Long id,
String title,
User user
}
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)
}
...
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?
Normally I implemented my class in following manner,
Entity : Contain all data related to your actual database object. (Additional data by @transient annotation)
DTO : Customize class which creates to provides compatibility between Entity and required JSON.
Mapper : It can convert Entity to DTO and vice versa.
In sort, Create entity for database object, n numbers of DTO for verity of need and using mapper class convert it to appropriate type and write this terms in your service class. So based on your need create DTO and in service class implement logic for get them all together. (In best way use interface or inheritance when wants to bind multiple DTO in single entity or scattered it.)
Now comes to your question,
I wonder how I can convert DTO to Entity when if property value present in Entity did not exist in DTO.
Answer : Convert it using Mapper class. As per I define above Entity is database object and DTO is expected JSON. So doesn't matter it compulsory exist in your DTO. You can customize DTO as per your need.
The repository is not being called directly from the controller.
Answer : As obvious you have to do that and right way to implementation.
Should I create an additional DTO that has the same properties as user entity? java
Answer : Yes you can but if it compulsory required. My suggestion is follow structure as I defined earlier it becomes helpful in future also, Suppose new kind of data you need you just have to add one function in mapper class and it return data accordingly, you also modify from single place and use every where.
This suggestion for based your code.
UserDto userDto = userService.findUser(userId)
My personal suggestion as developer,
Create one JHipster project once and check their flow it gives you good idea regarding how to create structure in professional way.