Spring Boot中的分页循环关联数据

时间:2018-07-16 18:17:15

标签: java spring spring-mvc spring-boot spring-data-jpa

嗨,我正在尝试在春季靴子中实现分页。我有3张桌子。

1)帖子->像小推文一样存储帖子。

2)个人资料->用户详细信息

3)身份验证->用户身份验证表。

这三个表之间的关系如下。

String: clickL 728 1062-clickL 540 382-key h-key e-key l-key l-key o-
Set: clickL 728 1062
Word: clickL
FAIL
Set: clickL 540 382
Word: clickL
FAIL
Set: key h
Word: key
FAIL
Set: key e
Word: key
FAIL
Set: key l
Word: key
FAIL
Set: key l
Word: key
FAIL
Set: key o
Word: key
FAIL

当我按以下方式尝试邮寄表的分页

Post.java

 profile have OneToOne relation with Authentication.  
 profile have OneToMany relation with Post.

 authentication have OneToOne with Profile.

 Post have OneToOne with Profile.

PostRepository.Java

 @Entity
 public class Post {

     @OneToOne(fetch = FetchType.LAZY)
     private Profile profile;

     @Override
     public String toString() {
          return "Post [id=" + id + ", tweet=" + tweet + ", profile=" + profile + "]";
}

PersonPagingService .Java

 @Repository
  public interface PostRepository extends PagingAndSortingRepository<Post,Integer> {
      Post findById(int id);
  }

PostService.Java

 public interface PersonPagingService {

Page<Post> getAllPosts(Pageable pageable);

}

PostController.Java

@Service
public class PostService implements PersonPagingService {

    @Autowired
    private PostRepository postRepository;

    @Override
    public Page<Post> getAllPosts(Pageable pageable){
        return postRepository.findAll(pageable);
    }
}

我发送

的请求时

enter image description here

原始数据

RAW DATA of response

如果我要在POST.JAVA中删除关系,那么它工作正常。

请帮助我了解我在做什么错误。

**不必担心身份验证数据就是测试数据**

Profile.Java

@RestController
public class PostController{

    @GetMapping("/test")
    public List<Post> checkThesSignupEmailIsNew(Pageable pageable) {
       Page<Post> posts = PersonPagingService.getAllPosts(pageable);
       return posts.getContent();
    }
} 

它从数据库中获取一个帖子

@Entity
 public class Profile {

  @OneToMany(fetch=FetchType.LAZY, cascade= CascadeType.ALL, mappedBy = "profile")
  List<Post> posts; 

   @Override
   public String toString() {
    return "Profile [id=" + id + ", name=" + name + ", email=" + email + ", location=" + location + "]";
   }
}

enter image description here

3 个答案:

答案 0 :(得分:1)

从您的Entities返回Controllers并不是一个好主意。因为JSON之类的Jackson序列化程序将尝试使用其所有属性将您的实体序列化为JSON。而且由于您的对象是Hibernate代理,因此可能会导致一些问题。

您可能会从数据库中获取过多不需要的记录。

如果LazyInitiailzatinException试图获取尚未获取但Hibernate已关闭的惰性属性,则您可能会遇到Session

在双向关系的情况下,您将面临无限循环陷阱。

相反,最好为Model使用DTOEntities类并将Entity对象转换为ModelDTO对象并在这些对象中设置要包含在响应中的属性,然后将其返回。

答案 1 :(得分:0)

创建JSON时就像一个循环。我遇到了同样的问题,直到用@JsonIgnore注释了关系的一部分(等同于equals和hashcode(Lombok))。

答案 2 :(得分:0)

要防止无限循环,只需删除您在实体类中使用的相关实体的get方法。例如:

@OneToMany(fetch=FetchType.LAZY, cascade= CascadeType.ALL, mappedBy = "profile")
  List<Post> posts;

我假设您可能已经建立了posts的getter和setter方法,所以仅添加'setter'方法可以解决您的问题。