简体   繁体   English

REST Web服务以JSON返回多个实体

[英]REST web service returns more than one entity in JSON

I am using REST web service. 我正在使用REST Web服务。 I am trying to get one entity from the database, but my method returns a lot of same records. 我试图从数据库中获取一个实体,但是我的方法返回了很多相同的记录。 I am using EclipseLink JPA implementation. 我正在使用EclipseLink JPA实现。

Here is my entity: 这是我的实体:

@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;

My controller method: 我的控制器方法:

@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;
}

尝试对班级中的每个列表都使用fetch type lazy

@OneToMany(fetch = FetchType.LAZY)

Your code is typed-protected : you can only receive one News. 您的代码受类型保护:您只能收到一个新闻。 This news may have many Comments, and I suppose it's not a problem, and a even good idea to fetch them all eagerly. 这则新闻可能有很多评论,我想这不是问题,甚至是一个好主意,希望能尽快将它们全部拿走。

My first idea is that you must have fetch the wrong route, or have ambiguous routes. 我的第一个想法是,您必须获取错误的路由,或具有不明确的路由。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM