我有2个实体,用户和帖子。使用spring-boot
用户有很多帖子,而帖子有一个用户。我对它们进行了注释,如下所示。 当我请求数据库中的所有帖子时,它将返回如下的帖子列表。
POST 1和POST 2具有相同的User属性,并且其中只有一个可以获取相关的User。当另一个帖子首次有另一个不同的用户时,它可以获取该用户。
每个Post条目都需要完整的User对象。
(我使用龙目岛[@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;
}
答案 0 :(得分:0)
正如Michal Ziober所述,这是因为@JsonIdentityInfo批注。 它使对象可以一次序列化。