Return JpaRepository findAll() 方法中对象的浅拷贝

Return a shallow copy of an object in JpaRepository findAll() method

我正在尝试使用 JpaRepositoryfindAll() 方法检索实体列表,但我尝试检索的实体有许多其他对象 OneToMany里面的关系。

我有一个classProgram如下:

@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 的列表。

当我尝试检索程序时,我得到一个 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() 方法时删除嵌套对象。

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

我看到两个选择:

  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();