【问题标题】:JpaRepository returning child for the first item in the list and then only the id for the restJpaRepository 返回列表中第一项的子项,然后仅返回其余项的 id
【发布时间】:2022-01-08 06:59:21
【问题描述】:

我有以下Post 类:

@Entity
@Table(name = "posts")
@Getter
@Setter
@JsonIdentityInfo(      generator = ObjectIdGenerators.PropertyGenerator.class, 
                        property  = "id", 
                        scope     = Long.class)
public class Post {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    private String title;
    
    private String subtitle;
    
    private String content;
    
    private String img_url;
    
    @CreationTimestamp
    private Timestamp created_on;
    
    @UpdateTimestamp
    private Timestamp last_updated_on;
    
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "owner_id", nullable=false)
    @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
    private User creator;
    
}

以及以下扩展 JpaRepository 的存储库

@Repository
public interface PostRepository extends JpaRepository<Post, Long> {

    Optional<Post> findById(Long id);
    
    List<Post> findAll();
    
}

当在下面的控制器中返回findAll()的结果时,只有第一个创建者项目被完全发送,其余的只包含id:

@GetMapping("/news")
    public List<Post> getNews() {
        return postRepository.findAll();
    }

这是我得到的 JSON:

[
{"id":15,"title":"Title example #1","subtitle":"Subtitle example #1","content":"Lorem #1 ipsum dolor sit amet","img_url":null,"created_on":"2021-12-01T00:00:00.000+00:00","last_updated_on":"2021-12-01T00:00:00.000+00:00","creator":{"id":1,"username":"user-example","email":"blablabla@gmail.com","roles":[{"id":1,"name":"ROLE_USER"}]}}

,{"id":25,"title":"Title example #2","subtitle":"Subtitle example #2","content":"Lorem #2 ipsum dolor sit amet","img_url":null,"created_on":"2021-12-01T00:00:00.000+00:00","last_updated_on":"2021-12-01T00:00:00.000+00:00","creator":1}
]

为什么会这样?有没有办法为 JSON 数组中的每个元素获取整个子对象?

谢谢

编辑:添加了User

@Entity
@Table( name = "users", 
        uniqueConstraints = { 
            @UniqueConstraint(columnNames = "username"),
            @UniqueConstraint(columnNames = "email") 
        })
@DiscriminatorValue(value="USER")
public class User extends OwnerEntity {

    @NotBlank
    @NotNull
    @Size(max = 20)
    private String username;

    @NotBlank
    @NotNull
    @Size(max = 50)
    @Email
    private String email;

    @NotBlank
    @Size(max = 120)
    @JsonIgnore
    private String password;
    
    @CreationTimestamp
    private Timestamp created_on;
    
    @UpdateTimestamp
    private Timestamp last_updated_on;

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable( name = "user_roles", 
                joinColumns = @JoinColumn(name = "user_id"), 
                inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Set<Role> roles = new HashSet<>();

    @ManyToMany(fetch = FetchType.LAZY)
    private Set<Institution> institutions;
    
    @OneToMany(mappedBy="creator", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    protected Set<Post> posts;
    
    @ManyToMany(fetch = FetchType.LAZY)
    private Set<Institution> following;
}

编辑 2:添加 OwnerEntity 类

@Entity
@Table(name = "entities")
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn
@Getter
@Setter
@JsonIdentityInfo(      generator = ObjectIdGenerators.PropertyGenerator.class, 
                        property  = "id", 
                        scope     = Long.class)
public class OwnerEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    protected Long id;
    
}

【问题讨论】:

  • 您能否在您的问题中添加User 类?
  • 已编辑并添加,就是这样!比
  • 可以加OwnerEntity吗?谢谢!
  • 添加了OwnerEntity.java!
  • 跟我想的完全一样。请在下面查看我的答案;)

标签: spring spring-boot hibernate spring-data-jpa


【解决方案1】:

您的OwnerEntity 也有@JsonIdentityInfo。在其reference documentation 中,我们可以阅读以下内容:

Annotation 用于指示带注释类型的值或 属性应该序列化,以便实例包含 附加对象标识符(除了实际对象属性), 或作为由引用完整的对象 id 组成的引用 序列化。在实践中,这是通过序列化第一个 实例作为完整的对象和对象标识,以及其他对 对象作为参考值。

这完美地解释了为什么你会得到这样的 JSON。如果您不想这样做,只需删除 @JsonIdentityInfo,但它可能会在序列化双向关系时修复无限递归(您可以在以下在线资源 https://www.baeldung.com/jackson-bidirectional-relationships-and-infinite-recursion 中阅读更多相关信息)。

【讨论】:

  • 好的,所以我试了一下,效果很好。稍后我将不得不解决其他实体上的无限递归问题,也许我会在解决方案的上述部分进行返工。非常感谢,我会将其标记为已接受的答案。
  • 很高兴能帮到你 ;)
猜你喜欢
  • 1970-01-01
  • 2016-08-04
  • 1970-01-01
  • 1970-01-01
  • 2021-07-30
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 2021-02-13
相关资源
最近更新 更多