gpt4 book ai didi

java - @OneToMany 中未填充父实体。 hibernate 双向

转载 作者:行者123 更新时间:2023-11-29 07:26:33 24 4
gpt4 key购买 nike

嗨,Hibernate 新手,

我的实体类

@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: localhost: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;
}

请帮忙。

最佳答案

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

GET/users : 所有用户

GET at /users/1 : 用户 1 及其所有 child 的信息

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

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

当您调用 /users/101/posts/11001 时,端点将为您提供来自一个用户(id 101).

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

最快的方法是调用 /users 并在前端过滤您想要的帖子。

正确的方法是更改​​您的帖子模型 (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

关于java - @OneToMany 中未填充父实体。 hibernate 双向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51517862/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com