Reputation: 7
This is my UserDTO class which I am using to store values coming from UI.
public class UserDTO {
private String emailId;
private String password;
private String role;
// getters and setters
}
And this is the Entity class which deals with the database(i am using hibernate).
public class UserEntity {
@Id
@Column(name = "EmailId")
private String emailId;
@Column(name = "Password")
private String password;
@ManyToOne
@JoinColumn(name = "role_id", nullable = false)
RoleEntity role;
// getters and setters
}
And following is the RoleEntitity Class which is having a string role field.
public class RoleEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "role_id")
private int id;
@Column(name = "role")
private String role;
// getters and setters
}
I am getting user values from UI in request body.
@RequestMapping(value = "/createUser", method = RequestMethod.POST, produces= {"application/json"})
public ResponseEntity<String> createUser(@RequestBody UserDTO userDTO) {
return new ResponseEntity<String>(adminService.createUser(userDTO), HttpStatus.CREATED);
}
Here, I want to map the role from UserDTO to the RoleEntity. I am using dozer mapper map method to map DTO to Entity. dozerMapper is an object of DozerBeanMapper. userDTO is an object of UserDTO and userEntity an object of UserEntity.
//In createUser(UserDTO userDTO)
dozerMapper.map(userDTO, userEntity);
Errors:
MapId: null
Type: null
Source parent class: com.iiminds.crm.dto.UserDTO
Source field name: role
Source field type: class java.lang.String
Source field value: Admin
Dest parent class: com.iiminds.crm.entity.UserEntity
Dest field name: role
Dest field type: com.iiminds.crm.entity.RoleEntity
org.dozer.MappingException: Illegal object type for the method 'setRole'.
Expected types:
com.iiminds.crm.entity.RoleEntity
Actual types:
java.lang.String
2018-10-29 16:15:39.229 ERROR 11516 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[.[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [/crm] threw exception [Request processing failed; nested exception is org.dozer.MappingException: Illegal object type for the method 'setRole'.
Expected types:
com.iiminds.crm.entity.RoleEntity
Actual types:
java.lang.String] with root cause
Upvotes: 0
Views: 1750
Reputation: 2592
It is because in your UserDTO.java
you have role as String
while in UserEntity.java
type of role is RoleEntity
. You cannot map String to RoleEntity
. However, in mapping file you can exclude role field from mapping like:
<class-a>UserDTO</class-a>
<class-b>UserEntity</class-b>
<field-exclude>
<a>role</a>
<b>role</b>
</field-exclude>
P.S: Fill fully qualified class name.
Then you can manually create RoleEntity
and set it to role in UserEntity
Upvotes: 0