开发者社区> 问答> 正文

在JpaRepository findAll()方法中返回对象的浅表副本

我正在尝试使用JpaRepository的findAll()方法来检索实体列表,但是我要检索的Entity OneToMany内部有许多其他Objects作为Relationship。

我的课Program如下:

@Entity
public class Program extends BaseEntity {

    private String programTitle;

    private String description;

    private String programType;

    private String price;

    @OneToMany(mappedBy = "program", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
    @JsonManagedReference(value = "program-benefit")
    private List<Benefit> benefits = new ArrayList<>();

    @Column(name = "category")
    private String category;
    //Getters and setters
    }

如您所见,其中有一个列表Benefits。

当我尝试检索Program时,我得到的JSON也具有“两个对象”列表,例如:

我得到的回应:

{
    "id":1,
    "category": "cardio",
    "description": "exercies for cardio",
    "benefit": [
        {
            "description": "good for healt"
        },
        {
            "description": "string2"
        }
    ],
    "price": "50",
    "program_title": "cardio demo"
}

但是我想要像这样的对象的浅表副本

预期回应:

{
    "id":1,
    "category": "cardio",
    "description": "exercies for cardio",
    "price": "50",
    "program_title": "cardio demo"
}

我尝试进行更改,CascadeType但是它将停止在所有API中显示嵌套对象,我只希望在调用findAll()method 时删除嵌套对象。

当我调用该findAll()方法时,有没有办法停止显示嵌套对象?

问题来源:Stack Overflow

展开
收起
montos 2020-03-27 16:36:53 1762 0
1 条回答
写回答
取消 提交回答
  • 我看到两个选择:

    1. 如果要避免序列化获取的字段,请使用@JsonIgnore。

    2. 如果您根本不想获取这些字段,请创建一个DTO并编写一个自定义查询以将结果映射到该字段:

    public class ProgramDTO {
    
        private Long id;
        private String programTitle;
        private String description;
        private String programType;
        private String price;
    
    }
    

    接着:

    entityManager
        .createQuery("select new ProgramDTO(p.id, p.programTitle, p.description, p.programType, p.price from Program p")
        .getResultList();
    

    回答来源:Stack Overflow

    2020-03-27 16:37:44
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
建立联系方法之一 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载

相关实验场景

更多