Home > Software design >  How to prevent model mapper to not map the lazy loaded collection in spring data jpa?
How to prevent model mapper to not map the lazy loaded collection in spring data jpa?

Time:02-16

I am making a rest api using spring boot, sprint data jpa and mysql. I have user and role entity. User can have many roles and roles can have many users. I am modelmapper dependency for converting entity to dto. I have set the roles collection fetch type to lazy. But modelmapper is calling the getRoles method on user entity. How to stop it. Please help me.

Note: User and UserDTO has same fields.

User:

@Entity
@Table(name = "users")
public class User  {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String username;
private String password;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
        name = "user_roles",
        joinColumns = @JoinColumn(name = "user_id",referencedColumnName = "id"),
        inverseJoinColumns = @JoinColumn(name = "role_id",referencedColumnName = "id")
)
private Set<Role> roles;
}

Role:

@Entity
@Table(name = "roles")
public class Role  {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String roleName;
}

UserService:

@Service
@Transactional
public class UserService {

@Autowired
private ModelMapper mapper; 
@Autowired
private UserRepository userRepository;

public UserDTO find(Integer id){
   User user = userRepository.findById(id).get();
   return mapper.map(user,UserDTO.class);
}
}

CodePudding user response:

You have to declare a skip property.

Example:

TypeMap<Game, GameDTO> propertyMapper = this.mapper.createTypeMap(Game.class, GameDTO.class);
propertyMapper.addMappings(mapper -> mapper.skip(GameDTO::setId));

Reference: https://www.baeldung.com/java-modelmapper

CodePudding user response:

You can applied a conditional skip operation. https://stackoverflow.com/a/38729404/2039546

But when you mark your @OneToMany relationship as a lazy one, it's your Set that will actually become lazy rather than getRoles().

So if you write a conditional statement, the fetch process will happen as soon as you check if the roles exist.

Shortly, first you have to check how the children entites will return conditionally, then you need to do the conditional field jump, so you will get what you want.

  • Related