Spring Data Jpa Sping Boot parent child自引用关系将子记录返回为null

bf1o4zei  于 11个月前  发布在  Spring
关注(0)|答案(1)|浏览(192)

我正在使用Sping Boot 和Spring Data Jpa处理一个Rest API端点。我面临的问题是子记录为null。以下是关于我接收的数据的代码和截图。
首先,返回数据的截图。Json returned Data
以下是我的模型“文章”

@Entity
//@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties({"hibernate_lazy_initializer", "handler"})
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
public class Article {
@Id
@Getter
@Setter
@EqualsAndHashCode.Include
private Long id;

@Getter
@Setter
@EqualsAndHashCode.Include
private Long parent_id;

@Getter
@Setter 
@EqualsAndHashCode.Include
private String name;

@ManyToOne(fetch = FetchType.LAZY)
@Getter
@Setter
private Article article;

@OneToMany(fetch = FetchType.LAZY, mappedBy = "article")
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
@Setter
private Set<Article> subArticles;

@JsonIgnore
public Set<Article> subArticles() {
    return subArticles;
}
}

字符串
以下是我的DTO

@Data
@Builder
//@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonNaming(PropertyNamingStrategies.SnakeCaseStrategy.class)
@JsonIgnoreProperties({"hibernate_lazy_initializer", "handler"})
public class ArticleDTO {

private Long id;
private String name;
private Long parent_id;
private Article article;
private Set<Article> subArticle;

}


以下是我的控制器:

@RestController
@RequestMapping("/api/v1/article")
public class ArticleController {

@Autowired
private ArticleRepository articleRepository;

@GetMapping("/{id}")
public ResponseEntity<ArticleDTO> getAllArticles(@PathVariable("id") Long id) {
    
    // here first show simple result/
    return articleRepository
            .findById(id)
            .map(mapToArticleDTO)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
}

@GetMapping("/{id}/siblings")
public ResponseEntity<Set<ArticleDTO>> getAllSiblings(@PathVariable("id") Long id) {
    return articleRepository.findById(id).map(findSubArticles).map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
}

private Function<Article, ArticleDTO> mapToArticleDTO = a -> ArticleDTO.builder()
                                                        .id(a.getId())
                                                        .name(a.getName())
                                                        .parent_id(a.getParent_id())
                                                        .build();

private Function<Article, Set<ArticleDTO>> findSubArticles = article -> article.getArticle().subArticles().stream()
        .map(a -> ArticleDTO.builder().id(a.getId()).name(a.getName()).build()).collect(Collectors.toSet());
}


以下是我的Repository:

@Repository
public interface ArticleRepository extends JpaRepository<Article, Long>{

}


以下是我的数据库记录截图Database records
任何指导,我去错误的地方将不胜感激。

mdfafbf1

mdfafbf11#

总之,Lazy fetching是在transaction下工作的,用@Transactional标记你的类。

相关问题