【发布时间】:2016-07-05 17:32:12
【问题描述】:
我正在使用 Spring Boot 来实现 rest api。共有三个实体SeqTb、PairTb 和GroupTb,它们是嵌套的。 SeqTb 与PairTb 有很多关系。 PairTb 与 SeqTb 具有单对多关系,也与 GroupTb 具有多对多关系。
//SeqTb.java
@Entity
@Table(name="SEQ_TB")
public class SeqTb implements Serializable {
.......
@ManyToOne
@JoinColumn(name="PAIR_ID")
private PairTb pairTb;
......
}
// PairTb.java
@Entity
@Table(name="PAIR_TB")
@NamedQuery(name="PairTb.findAll", query="SELECT p FROM PairTb p")
public class PairTb implements Serializable {
@ManyToOne
@JoinColumn(name="GROUP_ID")
private GroupTb groupTb;
@OneToMany(mappedBy="pairTb", cascade=CascadeType.ALL)
private List<SeqTb> seqTbs;
}
//GroupId.java
@Entity
@Table(name="GROUP_TB")
public class GroupTb implements Serializable {
//bi-directional many-to-one association to PairTb
@OneToMany(mappedBy="groupTb", cascade=CascadeType.ALL)
private List<PairTb> pairTbs;
}
在我的控制器中,带有 analysisId 的 GET 请求是通过以下方式处理的:
@RequestMapping(
value = "/api/seqs/{analysis_id}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<SeqTb> getSeqByAnalysisId(@PathVariable("analysis_id") String analysis_id) {
SeqTb seq = seqService.findByAnalysisId(analysis_id);
return new ResponseEntity(seq, HttpStatus.OK);
}
我还创建了一个扩展接口 SeqService 的 bean 类 SeqServiceBean,该接口又调用来自以下 JPA 存储库的方法进行查询。
//SeqRepository.java
@Repository
public interface SeqRepository extends JpaRepository<SeqTb, Integer> {
@Override
public List<SeqTb> findAll();
public List<SeqTb> findByAnalysisId(String analysisId);
}
当我使用 SeqTb.PairTb == null 查询 SeqTb 对象时,该 api 工作正常。但是,如果我在 url 中输入的 analysisId 属于 SeqTb 记录,该记录与 pairId 相关联,而 pairId 又属于 groupId,则程序会发疯。下面是输出,第一部分输出是正确的(粗体字)。之后,它继续循环打印 PairTb 和 GroupTb(重复关键字 pairTb、groupTb)。
{"rowId":8,"analysisId":"cce8d2c2-a6dc-4ee9-ba97-768f058abb50","analyteCode":"D","center":"UCSC", "pairTb":{"rowId":4,"pairCode":"01ad975d-c2ed-4e4d-bd3b-c9512fc9073c","groupTb":{"rowId": 1,"groupName":"PAWG_pilot-50","pairTbs":[{"rowId":1,"pairCode":"00ad0ffe-2105-4829-a495-1c2aceb5bb31", "groupTb":{"rowId":1,"groupName":"PAWG_pilot-50","pairTbs":
同时我从 tomcat 服务器收到很多错误:
Caused by: java.lang.IllegalStateException: getOutputStream() has already been called for this response
at org.apache.catalina.connector.Response.getWriter(Response.java:565) ~[tomcat-embed-core-8.0.32.jar:8.0.32]
at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:212) ~[tomcat-embed-core-8.0.32.jar:8.0.32]
如何忽略实体内的嵌套实体对象,只获取含义列?
【问题讨论】:
标签: rest spring-boot entity spring-data-jpa