Spring Jpa一对多关系在其余响应中

时间:2018-06-21 15:36:47

标签: hibernate spring-boot spring-data-jpa hibernate-mapping

Authors     
Author_ID (PK)  Author_name genre_group
1               Peter       G01


Genres      
genre_group genre          Description
G01         Action         Action…………..
G01         Adventure      Adventure………….
G01         Mystery        Mysrie………………..

我上面有两个桌子。我想以如下所示的休息格式实现响应

1
Peter
[Action,Adventure,Msytery]

有人可以告诉我如何定义我的实体类,映射和存储库以实现上述响应吗?

1 个答案:

答案 0 :(得分:0)

想法是 Authors Genere 实体的创建响应类。

class AuthorResponse {
    private long authorId;
    private String authorName;
    private String genres;

}

class GenresResponse {
   private String genre;

  public String toString(){
      return this.genre;
  }
}

public static GenresResponse generResponse(Genre genere) {
        GenresResponse response = new GenresResponse ();
        BeanUtils.copyProperties(genere, response);
        return response;
    }

public static AuthorResponse authorResponse(Author author) {
        AuthorResponse response = new AuthorResponse();
        BeanUtils.copyProperties(author, response);

        // Not really required to convert. But I suggest to clear separation between
       // entity class and  entity response class
        List<GenerResponse> generes = author.getGenres().stream().
          map(ModelConverter::generResponse)
         .collect(Collectors.toSet()));


       response.setGenre(generes.toString());
        return response;
    }


 PSVM {
   Author author = <get from repository>
   authorResponse(author)
 }