REST Web服务在JSON中返回多个实体

时间:2015-11-24 11:54:13

标签: java json rest jpa

我正在使用REST网络服务。我试图从数据库中获取一个实体,但我的方法返回了很多相同的记录。我正在使用EclipseLink JPA实现。

这是我的实体:

@Entity
@Table(name = "News")
public final class News implements Serializable, IEntity {

/**
 * For deserialization with no exception after modification.
 */
private static final long serialVersionUID = 3773281197317274020L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "news_id", precision = 0)
private Long newsId; // Primary key

@Column(name = "title")
private String title;

@Column(name = "short_text")
private String shortText;

@Column(name = "full_text")
private String fullText;

@Temporal(TemporalType.DATE)
@Column(name = "creation_date")
private Date creationDate;

@Temporal(TemporalType.DATE)
@Column(name = "modification_date")
private Date modificationDate;

@OneToMany(fetch = FetchType.EAGER, mappedBy = "news")
private List<Comment> commentsList;

@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "news_tag", joinColumns = { @JoinColumn(name = "news_id") }, inverseJoinColumns = { @JoinColumn(name = "tag_id") })
private Set<Tag> tagSet;

@ManyToOne(fetch = FetchType.EAGER)
@JoinTable(name = "news_author", joinColumns = { @JoinColumn(name = "news_id") }, inverseJoinColumns = { @JoinColumn(name = "author_id") })
private Author author;

我的控制器方法:

@RequestMapping(value = { "/singleNews/{newsId}" }, method = RequestMethod.GET)
public @ResponseBody News showSingleNews(@PathVariable("newsId") Long newsId) throws ServiceException {
    News news = newsService.getSingleNewsById(newsId);
    news.setCommentsList(commentService.getListOfCommentsByNewsId(newsId));
    return news;
}

2 个答案:

答案 0 :(得分:1)

尝试对您班级中的每个列表使用lazy类型lazy

@OneToMany(fetch = FetchType.LAZY)

答案 1 :(得分:1)

您的代码受版税保护:您只能收到一条新闻。这个消息可能有很多评论,我认为这不是一个问题,甚至是一个好主意,所有人都热切地接受它们。

我的第一个想法是你必须获取错误的路线,或者有不明确的路线。