父实体未填充在@OneToMany中。休眠双向

时间:2018-07-25 11:32:51

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

嗨,新手进入休眠状态,

我的实体类

@Entity
public class User {

    @Id
    @GeneratedValue//How to restrcit by passing id from response
    @JsonIgnore
    private Integer userId;

    @OneToMany(mappedBy = "user")
    private List<PostEntity> postEntity;

}



@Entity
@Table(name="post")
public class PostEntity {

    @Id
    @GeneratedValue
    @JsonIgnore
    @ApiModelProperty(required=false)
    private Integer id;

    @ManyToOne(fetch=FetchType.LAZY)
    private User user;
}

当我获取用户时,也会填充其填充的Post实体。

URI:http://localhost:8080/jpa/users

[
 {
     "name": "Abdul",
     "birthDate": "2018-07-25T01:29:51.895+0000",
     "postEntity": [
         {
             "description": "My Fourth Post"
         },
         {
             "description": "My First Post"
         },
         {
             "description": "My Second Post"
         }
     ]
 },
 {
     "name": "Anji",
     "birthDate": "2018-07-25T01:29:51.903+0000",
     "postEntity": []
 },
 {
     "name": "Naren",
     "birthDate": "2018-07-25T01:29:51.903+0000",
     "postEntity": []
 }
]

,但情况并非相反。当我获取帖子时,其跳过的用户实体。

URI:本地主机:8080 / jpa / users / 101 / posts / 11001 响应:

{
    "description": "My First Post"
}

为什么在上述JSON响应中未填充用户信息。

获取方法:

用户:

@GetMapping("/jpa/users")
public List<User> retAll(){
    return userRepository.findAll();
}

帖子:

@GetMapping("/jpa/users/{uid}/posts/{pid}")
public Resource<PostEntity> postE(@PathVariable int uid,@PathVariable int pid) {
    Optional<PostEntity> post = postRepository.findById(pid);
    if (!post.isPresent()) {
        throw new UserNotFoundException("POst");
    }

    PostEntity ePost = post.get();
    Resource<PostEntity> resource = new Resource<PostEntity>(ePost);
    return resource;
}

请帮助。

2 个答案:

答案 0 :(得分:3)

这实际上是REST应该工作的预期方式。

GET/users:所有用户

GET /users/1:用户1及其所有子级的信息

GET/users/1/posts:用户1的所有帖子

GET/users/1/posts/10:来自用户1的帖子10及其所有子级的信息

在您呼叫/users/101/posts/11001时,端点将为您提供一个用户(id 101)的一个帖子(id 11001)的信息。

有两种获取父级信息的常用方法:

最快的方法是只调用/users并在前端过滤所需的帖子。

right 的方式将更改帖子(PostEntity.java)的模型以包含其“父” User对象,因此,当您进行REST调用时,发布后,将填充用户对象。

进一步阅读:

https://softwareengineering.stackexchange.com/questions/274998/nested-rest-urls-and-parent-id-which-is-better-design

也许最好阅读一些REST最佳实践:

https://hackernoon.com/restful-api-designing-guidelines-the-best-practices-60e1d954e7c9

答案 1 :(得分:2)

尝试使用FetchType

@Entity
public class User {

    @Id
    @GeneratedValue//How to restrcit by passing id from response
    @JsonIgnore
    private Integer userId;

    @OneToMany(mappedBy = "user", fetch=FetchType.EAGER)
    private List<PostEntity> postEntity;

}

当心表演。