【问题标题】:Spring Jpa one to many relationship in rest reponseSpring Jpa在休息响应中的一对多关系
【发布时间】:2018-12-01 00:28:22
【问题描述】:
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]

谁能告诉我应该如何定义我的实体类、映射和存储库以实现上述响应?

【问题讨论】:

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


    【解决方案1】:

    想法是为 AuthorsGenere 实体创建响应类。

    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)
     }
    

    【讨论】:

    • 使用 callicoder.com/… 查看一对多 springJPA 示例。从数据库中获取作者详细信息后,您可以按照我的回答。
    猜你喜欢
    • 2023-01-16
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 2019-01-24
    • 2017-08-19
    相关资源
    最近更新 更多