I\'m having trouble with a many to many relation with JPA. My code looks as follows:
The Sensor class:
@Entity
@Table(name = \"sensor\")
@Data
@NoArg
When User
serialized for the response, all getter methods of User
's fields are called.
So, User
relational field sensorLinks
's getter are also called to set value. This happened recursively. That's cause of infinite recursion.
It's better to not use Entity as a response. Create a DTO class for User
then map User
entity value into DTO then send response. Don't use any Enity class again into DTO then it will result same problem
For dynamically map one model to another you can use ModleMapper
public class UserDTO {
//Fields you want to show in response & don't use enity class
private Set<LinkDTO> sensorLinks;
}
public class LinkDTO{
//Fields you want to show in response &don't use enity class
}
public User getUserByEmail(@PathVariable("email") String email) {
User user = userRepository.findByEmail(email).orElse(null);
UserDTO userDto = merge(user,UserDTO.class)
return userDto;
}
public static <T> void merge(T source, T target) {
ModelMapper modelMapper = new ModelMapper();
modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
modelMapper.map(source, target);
}
It's working! This post helped: https://stackoverflow.com/a/57111004/6296634
Seems that you should not use Lombok @Data
in such cases.