【问题标题】: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】:
想法是为 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)
}