【发布时间】:2018-07-25 11:32:50
【问题描述】:
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;
}
当我获取 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;
}
请帮忙。
【问题讨论】:
-
这取决于您获取的方式。如果您在一次交易中获取它,它将正常工作。
-
你在 PostEntity 中有
getUser方法吗? -
我有合适的 getter 和 setter。不过我还没有发帖。
标签: java spring hibernate spring-boot spring-data-jpa