我有 2 个名为 Post 和 PostDetails 的实体类。两者都使用 MapsId
和共享主键进行一对一关系映射,如下所示。
帖子.java
@Entity
@Table(name = "post")
@Data
public class Post implements Serializable
{
private static final long serialVersionUID = -6698422774799518217L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NaturalId
@Column(name = "title")
private String title;
@OneToOne(mappedBy = "post", cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
private PostDetail detail;
}
帖子详情.java
@Entity
@Table(name = "post_detail")
@Data
public class PostDetail implements Serializable
{
private static final long serialVersionUID = -6699482774799518217L;
@Id
private Long id;
@Column(name = "created_on")
private Date createdOn;
@Column(name = "created_by")
private String createdBy;
@OneToOne(fetch = FetchType.LAZY)
@MapsId
@JoinColumn(name = "id")
@JsonIgnore
private Post post;
}
后控制器.java
@RestController
@RequestMapping("/api/v1/post")
public class PostController
{
private final PostRepository postRepository;
private final PostDetailRepository postDetailRepository;
public PostController(PostRepository postRepository, PostDetailRepository postDetailRepository)
{
this.postRepository = postRepository;
this.postDetailRepository = postDetailRepository;
}
@GetMapping(path = "/create")
public List<Post> createAndGetPosts()
{
Post post=new Post();
post.setId(new Random().nextLong());
post.setTitle("First Post");
post=postRepository.saveAndFlush(post);
PostDetail postDetail =new PostDetail();
postDetail.setCreatedBy("Admin");
postDetail.setCreatedOn(Date.from(Instant.now()));
postDetail.setPost(post);
postDetailRepository.saveAndFlush(postDetail);
return postRepository.findAll(Sort.by(Sort.Direction.DESC,"id"));
}
}
在Post控制器类中,我创建Post对象(将其保存为DB(,然后将其传递给PostDetail对象,然后使用Spring Data JPA将其保存到数据库。一切都按预期工作。但是当我立即获取记录列表时,通过postRepository.findAll(Sort.by(Sort.Direction.DESC,"id"));
方法,我在 Post 中收到 PostDetail 对象的值null
如下所示。
响应:
[
{
"id": 2,
"title": "First Post",
"detail": null
},
{
"id": 1,
"title": "Post1",
"detail": {
"id": 1,
"createdOn": "2019-06-21T03:31:43.000+0000",
"createdBy": "Admin"
}
}
]
但是当我从列表的前端再次发送请求时,我得到了正确的响应。我试图在请求之前放置刷新语句和第二个 findAll(( 语句,但没有任何效果。
发生这种情况是因为您收到从saveAndFlush
返回并存储在变量中的完全相同post
实例。
休眠不会更新Post.detail
,当你执行postDetail.setPost(post)
。
要修复它,您可以手动设置detail
或在保存后从缓存中逐出Post
实例,从而强制休眠以从数据库重新加载它。