Mapping and updating DTO in a database with Java, Dozer and Hibernate

I use Dozer to map Hibernate objects to their DTO. A simplified sample class is as follows:

@Entity public class Role { @Id @GeneratedValue @Column(name="RoleId", nullable=false) public int roleId; @Column(name="RoleName", nullable=false) @NotEmpty public String roleName; //get + set (not for the roleId since its autogenerated) } 

  public class RoleDTO { private int roleId; private String roleName; public RoleDTO(int roleId, String roleName) { this.roleId = roleId; this.roleName = roleName; } public RoleDTO() {} //gets + sets } 

Now the display works fine, but I have a problem trying to update. Let's say I have a role (1, "Administrator") in my database. My view first generates a DTO with updated fields:

 RoleDTO roleDTO = new RoleDTO(1, "admin"); 

In the end, the class that is saved in the role receives the DTO and converts it to the Entity class through Dozer to save the changes:

 Role role = DozerMapper.map(roleDTO,Role.class); 

At this point, my role object lost its identifier, apparently because the identifier column is defined as auto-increment, and I obviously cannot update the object with a null identifier.

So, how do I approach this problem so that the identifier and updated fields display all the objects? I could always bring the entity object to sleep mode and update each of my fields with the ones in the DTO and save it back, but this will defeat the whole purpose of using Dozer.

Thanks for any help.

+4
source share
3 answers

In this case, this is the perfect approach to provide an installer for the roleId for the Role object. Then the bulldozer will set the identifier. (In addition, I assume that your fields in Role are not public.)

With Dozer, you create an entity from DTO. At this point, the object is separated, that is, not associated with a Hibernate session. Then you should use session.merge(role) to save the changes.

+6
source
  @Autowired private RoleDao roleDao; @Transactional(readOnly = false) public void updateRole(RoleDTO roleDTO) { Role role = beanMapper.map(roleDTO, Role.class); roleDao.update(role); } 

You can create a Role Dao class and make a link in the manager class where you are mapping, and make an update method to update your Role class in GenericDao, where you defined the hibernate update method to call it, and your job is done.

+4
source

You do not need to merge. Dozer allows you to apply changes to an object.

 Role role = <entitymangaer>.find("id", Role.class); role = beanMapper.map(dto, role); role.update(); 
0
source

Source: https://habr.com/ru/post/1345733/


All Articles