休眠 | ManyToOne 关系获取对象一次

Hibernate | ManyToOne relation fetchs object once

我有 2 个实体,用户和 Post。使用 spring-boot

用户有很多帖子,Posts 有一个用户。我对它们进行了注释,如下所示。 当我请求数据库中的所有帖子时,它 returns 一个 Post 的列表,如下所示。

POST 1 和 POST 2 具有相同的用户 属性,并且只有其中一个可以获取相关用户。当另一个 Post 第一次拥有另一个不同的用户时,它可以获取该用户。

我需要每个 Post 条目的完整用户对象。

(我用的是龙目岛[@Data])

结果 (json)

[{
    "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
    }
}]

Post.java

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

User.java

@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 注释。 它使对象被一次性序列化。