JPA: Many to many relationship - JsonMappingException: Infinite recursion

前端 未结 2 1172
无人及你
无人及你 2021-01-16 21:42

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         


        
相关标签:
2条回答
  • 2021-01-16 22:25

    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);
      }
    
    0 讨论(0)
  • 2021-01-16 22:30

    It's working! This post helped: https://stackoverflow.com/a/57111004/6296634

    Seems that you should not use Lombok @Data in such cases.

    0 讨论(0)
提交回复
热议问题