java 如何在springboot中返回子实体沿着父实体详细信息

vu8f3i0k  于 2023-05-27  发布在  Java
关注(0)|答案(1)|浏览(183)

我想得到贷款的详细资料沿着每笔贷款的父母的详细资料,但我得到的只是孩子的详细资料,而不是父母的详细资料。
Loan为子实体,User为父实体

Pageable pageable = PageRequest.of(page, size);
Page<Loan> loanPage= this.loanRepo.findByStaffIdAndDateBetween(staffId, startDate, endDate, pageable);

List<Loan> modifiedLoans = loanPage.stream().map(ele-> {
ele.setUser(ele.getUser); 
                    return ele; }).collect(Collectors.toList());

父条目

@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private Long mobile;
    private String name;
    private String email;

    @ToString.Exclude
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true)
    @JsonIgnore
    private List<Loan> loan = new ArrayList<>();

}

儿童Enity

@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
@JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "@id")
public class Loan {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;    
    private String status;  

    @ToString.Exclude
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    @JsonIgnore
    private User user;
}
qyyhg6bp

qyyhg6bp1#

您可以在这里使用@JsonManagedReference@JsonBackReference来处理Jackson中的双向关系。如果您不熟悉此查找详情here
像这样替换parentEntity

@JsonManagedReference
    @ToString.Exclude
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "user", orphanRemoval = true)
    @JsonIgnore
    private List<Loan> loan = new ArrayList<>();

和子实体

@JsonBackReference
    @ToString.Exclude
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id")
    @JsonIgnore
    private User user;

相关问题