我有2个实体,User和Post。使用弹簧靴
用户有很多帖子,帖子有一个用户。我注释了它们,如下所示。当我对DB中的所有帖子发出请求时,它会返回如下所示的帖子列表。
POST 1和POST 2具有相同的User属性,其中只有一个可以获取相关的User。当另一个帖子第一次有另一个不同的用户时,它可以获取该用户。
我需要每个Post条目的完整User对象。
(我用Lombok [@Data])
[{
"id": 1,
"context": "POST 1",
"user": {
"id": 1,
"username": "user_1",
"picture": "pic_1",
"is_active": true,
"is_verified": true
}
},
{
"id": 2,
"context": "POST 2",
"user": 1,
},
{
"id": 3,
"context": "POST 3",
"user": {
"id": 2,
"username": "user_2",
"picture": "pic_2",
"is_active": true,
"is_verified": true
}
}]
@Data
@Entity(name = "Post")
@Table(name = "post")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Post extends PersistentObject implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String context;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
@JsonIgnoreProperties(ignoreUnknown = true, value = {"password", "isActive", "isVerified", "blockedUsers"})
private User user;
}
@Data
@Entity(name = "User")
@Table(name = "user")
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler", "posts", "following_locations", "blocked_users"})
@DynamicUpdate
public class User extends PersistentObject implements Serializable
{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@JsonProperty("username")
private String username;
@JsonProperty("password")
private String password;
@JsonProperty("picture")
private String picture;
@JsonProperty("is_active")
private Boolean isActive;
@JsonProperty("is_verified")
private Boolean isVerified;
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
@JsonBackReference(value = "user_posts")
@JsonProperty("posts")
private List<Post> posts;
@OneToMany(mappedBy = "id", fetch = FetchType.LAZY)
@JsonBackReference(value = "user_following_locations")
@JsonProperty("following_locations")
public List<Location> followingLocations;
@OneToMany(mappedBy = "blocker", fetch = FetchType.LAZY)
@JsonProperty("blocked_users")
private List<BlockedUser> blockedUsers;
}
正如上面提到的Michal Ziober,这是因为@JsonIdentityInfo注释。它使对象一次性序列化。