Reputation: 386
I have a DTO called User whch has the fields userFirstName,userLastName .Also I have a entity called UserEntity that has the fields id,userFirstName,userLastName.I am not having id field in my JSON payload as that will be autogenerated,so how will the JSON fields map to UserDTO.And i also cannot remove the id field from UserDTO as I am using the same userDTO class to show the list of users where I need to show the id attribute in JSON.How can I use the same USERDTO class for POST and GET request type where in POST request we don't send a id attribute in JSON body and in GET response we need id attribute My entity class:
@Entity
@Table(name = "usr")
public class User implements Serializable {
public User() {
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "firstName")
private String userFirstName;
@Column(name = "lastName")
private String userLastName;
// fields with getters / setters for all the fields.
}
My DTO Class public class UserDTO {
private Long id;
private String userFirstName;
private String userLastName;
}
JSON POST request:
{
"userFirstName":"testuserFirstName",
"userLastName":"testuserLastName",
}
This is the response that I want to see when we do a GET request for a list of users :
{
"id":1,
"userFirstName":"testuserFirstName",
"userLastName":"testuserLastName",
}
Code snippet in the controller class method for POST Request
UserDTO requestPayloadData = gson.fromJson(json, UserDTO.class);
Upvotes: 0
Views: 914
Reputation: 2707
You actually need different objects for the task
I think you mix up the concepts of DTO (Data Transfer Object), which transfers data from your business logic to the front end, and DO (Data Object), which is there for persisting. So you normally never map a DTO to DB columns, this the the job of DOs
Another Suggestion, if you want to attain task with same classes.
While you copy data from UserDTO to User entity, skip the id filed
You can even remove the setter for id filed in User entity (if ORM got no issues)
Upvotes: 0