我创建了带有两个表的双向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.
答案 0 :(得分:1)
1)确保所有实体都实现equals
和hashCode
2):如果您是从Auction
到Bid
进行查询,则可以忽略Auction
:
@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY,optional = false)
@JoinColumn(name = "tender_join_id")
private Auction auction;
根据我的经验,直接将休眠代理传递给杰克逊(Jackson)进行解析,只会引发很多类似的问题。您可能需要考虑使用映射器层的某种DTO。只是一个建议,决定取决于您。