双向JPA映射时,Spring REST返回递归JSON

时间:2019-05-11 08:09:29

标签: java hibernate jpa recursion fetch

我创建了带有两个表的双向JPA一对多映射。双方都添加了惰性抓取功能。当我要求获取数据的一侧时,持久层将返回没有关系的正确结果集。 但是,当通过REST API获取这些数据时,它将返回一个长的JSON对象。 (递归数据)。

Java 8,Spring启动,Spring Data JPA


@Entity
@Table(name = "t_auction")
public class Auction {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "auction_name")
    private String tenderName;

    @OneToMany(fetch = FetchType.LAZY,cascade = CascadeType.ALL, mappedBy = "tender")
    private Set<Bid> bids;

}

`` Bidding Entity ---------------

@Entity
@Table(name = "t_bid")
public class Bid {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "bid_date")
    private Date bidDate;

    @ManyToOne(fetch = FetchType.LAZY,optional = false)
    @JoinColumn(name = "tender_join_id")
    private Tender tender;
}

`` Service Class ------------

public ResponseDto loadTenders(Tender tender) {
        ResponseDto responseDto = new ResponseDto();
        responseDto.setResponseItems(tenderRepository.findAll()); 
        return responseDto; // returns long JSON
    }

The actual result was a long JSON object.
The expected result is, Only requested entity without any mapped entities.

1 个答案:

答案 0 :(得分:1)

1)确保所有实体都实现equalshashCode

2):如果您是从AuctionBid进行查询,则可以忽略Auction

@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY,optional = false)
@JoinColumn(name = "tender_join_id")
private Auction auction;

根据我的经验,直接将休眠代理传递给杰克逊(Jackson)进行解析,只会引发很多类似的问题。您可能需要考虑使用映射器层的某种DTO。只是一个建议,决定取决于您。